SpringBoot学习_@PropertySource&@ImportResource&@Bean

@PropertySource:加载指定的配置文件

首先我们创建一个配置文件:
在这里插入图片描述
然后用@PropertySource指定它就可以了:

@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
public class Person {

运行测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot01HelloworldQuickApplicationTests {

    @Autowired
    Person person;
    @Test
    public void contextLoads() {
        System.out.println(person);
    }

}

控制台打印:
在这里插入图片描述

@ImportResource:导入Spring的配置文件,让配置文件里面的内容生效;

Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,不能自动识别;
先创建一个spring的配置文件:beans.xml
在这里插入图片描述
然后创建一个service:
在这里插入图片描述
然后把这个组件加入到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.nyh.springboot.service.HelloService"></bean>
</beans>

想让Spring的配置文件生效,加载进来;用@ImportResource标注在一个配置类上

@ImportResource(locations = {"classpath:beans.xml"})
@SpringBootApplication
public class SpringBoot01HelloworldQuickApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBoot01HelloworldQuickApplication.class, args);
    }
}

测试类:

	@Autowired
    org.springframework.context.ApplicationContext ioc;

    //测试容器中是否有这个组件
    @Test
    public void helloService(){
        boolean b = ioc.containsBean("helloService");
        System.out.println(b);
    }

控制台打印:
在这里插入图片描述

然而在开发时这样做很麻烦,要先写一个配置文件,然后再把配置文件加进来

@Bean

简便的方式:
SpringBoot推荐给容器中添加组件的方式;推荐使用全注解的方式
配置类@Configuration------>Spring配置文件,用配置类来代替配置文件
来写一个配置类:放在config文件夹下
在这里插入图片描述
@Configuration:告诉SpringBoot当前类是一个配置类,就是替代spring配置文件的

/*
* @Configuration:告诉SpringBoot当前类是一个配置类,就是替代spring配置文件的
*
* 在配置文件中用<bean></bean>添加组件,在配置类中用@Bean
*
* */
@Configuration
public class MyAppConfig {
    //@Bean的作用是将方法的返回值添加到容器中,容器中这个组件默认的id就是方法名
    @Bean
    //
    public HelloService helloService(){
        System.out.println("@Bean给容器中添加组件了");
        return new HelloService();
    }
}

然后把我们之前配置在主配置类上的@ImportResource(locations = {"classpath:beans.xml"})注释掉,再运行测试类看能不能添加进去
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_36901488/article/details/83042216