加载配置文件 @configration&@Bean&@ImportResource&@PropertySource

*springboot不是spring的加强版 ,在spring用的时候,注意加上扫包配置

1、importResource("classpath:beans.xml") 

xml加载外部文件:<context:property-placeholder  location="classpath:spring-common.xml"/>

1.1、PropertySource("classpath:config.properties")导入配置文件,使配置文件里的内容生效。

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

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

--------------

@Configuration

@ImportResource("classpath:/com/acme/properties-config.xml") public class AppConfig {

     }

    properties-config.xml

<beans> <context:property-placeholder location="classpath:/com/acme/jdbc.properties"/> </beans>

2、@configration

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
    String value() default "";
}

 @configration底层是含有@component,具有component的作用。

@configration可理解为spring的xml里的<beans>标签。

@configration作用在类上,配置spring容器的上下文。

    可以通过@Value("XXX")将配置文件里的变量值赋给自定义的变量

eg:  

@Value("${my.name}")
public String myName;

 

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

}

3、@configrationProperties是springboot的引入配置文件的注解

      可以定义一个实体类装载配置文件信息

*properties文件
....
myDev.name=张三
myDev.id=2
myDev.age=11

     

1、@Component
@configrationProperties(prefix="myDev")  //指定配置文件里的前缀
public class ConfigClass(){
    private String name;
    private String age;
    private String id;
.....
    set get 方法 
....
}

2、@configrationProperties(prefix="myDev")  //指定配置文件里的前缀
public class ConfigClass(){
    private String name;
    private String age;
    private String id;
.....
    set get 方法 
....
}



@Configuration
@EnableConfigurationProperties(ConfigClass.class)
public class MyWebServerConfiguration {
    @Autowired
    private ConfigClass configClass;
    /**
     *下面就可以引用configClass类里的配置了
    */
   public void setMyconfig() {
       String name= configClass.getName();
       // ...........
   }

      注:需要将配置的类扫描@Component注解把该bean注入到IOC容器中  或使用@EnableConfigurationProperties注解使其生效

 

 

注意:SpringBoot 用了@ImportResource 配置的拦截器就不起作用了。到Application启动类看一眼,项目中使用了@ImportResource 注解用于配置系统的参数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值