spring boot @propertySource @importResource @Bean [六]

@propertySource

指定property的配置源。

创建一个person.property:

然后修改person注解;

在运行test之后,结果为:

@importResource

这个importResource是用来兼容spring的。

HelloService:

package com.axm.demo.service;
public class HelloService {
    public  HelloService(){

    }
}

beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
   <bean id="helloService" class="com.axm.demo.service.HelloService"></bean>
</beans>

然后注入:

@SpringBootApplication
@ImportResource(locations = {"classpath:beans.xml"}) //关键
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

测试:

@Test
void contextLoads() {
    boolean has=ioc.containsBean("helloService");
    System.out.println(has);
}

结果:

然后再spring boot 有新的方式去注入服务:

添加一个配置文件:

@Configuration
public class MyApplication {
    @Bean
    public HelloService helloService(){
        return  new HelloService();
    }
}

然后就会自动注入这个HelloService 服务。

原文地址:https://www.cnblogs.com/aoximin/p/12906912.html