@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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值