@PropertySource、@ImportResource和@Bean

@PropertySource和@ImportResource

@PropertySource:加载指定的配置文件
@ImportResource:导入Spring配置文件,让配置文件里面配置的内容生效
这种方式注意要使用(location={classpath:xxx.xml})
另外在SpringBoot李边不推荐使用@ImportResource导入配置文件,推荐使用全注解方式导入配置文件

@PropertySource

我建了一个school.properties的文件,值配置了一个address

school.address=jiangnan
school.size=20
school.year=2022/6/3

配置类School

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

运行

School{
    
    address='jiangnan', year=Fri Jun 03 00:00:00 CST 2022, size=20, maps=null, objectList=null, grade=null}

@ImportResource

我们建一个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.xx.service.SchoolService"></bean>
</beans>

启动器导入改文件

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

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

正常启动,我使用测试类测试返回true

@Test
    public void testSchoolService(){
    
    
        boolean schoolService = ioc.containsBean("schoolService");
        System.out.println(schoolService);
    }

当然了还有另一种不需要配置文件的导入方式,那就是使用@Bean

我们创建一个配置类

@Configuration
public class SchoolConfig {
    
    

    @Bean
    public SchoolService schoolService(){
    
    
        System.out.println("我正在给容器中添加组件");
        return new SchoolService();
    }
}

使用@Configuration标注配置类
写一个方法将service放置进去
使用@Bean标注,这种方式不需要我们去xml里边配置
还是使用刚才的测试类

运行结果
true

猜你喜欢

转载自blog.csdn.net/weixin_43691960/article/details/112707142