*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
注解用于配置系统的参数。