(六)SpringBoot入坑-5@PropertySource和@ImportResource

文章目录

      • @PropertySource
      • @ImportResource
      • 推荐方式通过@Bean

@PropertySource

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

创建一个person.properties文件

person.last-name=李四
person.boss=true
#list 类型
person.lists=a,b,c
#map 类型
person.maps.k1=v1
#含有对象
person.dog.name=dp

在person类上加注解

@PropertySource(value = {"classpath:person.properties"})

@ImportResource

导入spring的配置文件,让配置文件生效

在Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别

测试

@Test
	public void testHelloService(){
		boolean b = ioc.containsBean("helloService");
		System.out.println(b);
	}

在主类中加入注解

@ImportResource(locations = {"classpath:bean.xml"})

以前spring的配置文件


<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.zyd.springboot.service.">bean>
beans>

推荐方式通过@Bean

/**
 * @Configuration : 指明当前类是一个配置类,就是来替代之前spring的配置文件
 * 在配置文件中用标签添加组件
 */
@Configuration
public class MyApplication {
    //将方法的返回值添加到容器中,容器中这个组件默认的id就是方法名
    @Bean
    public HelloService helloService(){
        System.out.println("配置ben生效了");
        return new HelloService();
    }
}

你可能感兴趣的:(springboot)