标签:width version bean getname group 为我 port ack path
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.7.RELEASE</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging-api</artifactId> <version>1.1</version> </dependency>
@Component //1 @PropertySource("classpath:aaa.properties")//2 public class ValueProperties { @Value("${name}")//3 private String name; @Value("${age}")//4 private Integer age; public void hello(){ System.out.println("my name : "+name+"| age: "+age); } }
1、@component 让Spring能够扫描到这个包
2、@PropertiesSource 读取加载classpath下的配置文件(只能是properties)
3、注入配置文件中的数据name 和age,
例如配置文件中的数据是这样的host.ip,那么注入时应该这样写${host.ip}
@ComponentScan//1 public class AppConfiguration { public static void main(String[] args) { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfiguration.class); applicationContext.getBean(ValueProperties.class).hello(); }
1、扫描包,这个类要在上面ValueProperties类的同级或更上层的包中
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> </dependency>
@Component//1 @ConfigurationProperties(prefix = "server.irich")//2
//这里不可以用@PropertySource加载配置文件
public class BootConfiguration { private String name; private Integer age; public void hello(){ System.out.println("my name : "+name+"| age: "+age); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; }
配置文件
server.irich.name=张国荣
server.irich.name=45
1、向容器中加入这个bean
2、加载配置文件中,prefix是只加载文件中指定前缀的数据
一定要有setter方法
注:1.5以后@ConfigurationProperties没有了locations这个功能,但他可以和@PropertySource、@Import组合使用
@ComponentScan //1 @EnableConfigurationProperties //2 @PropertySource("classpath:aaa.properties") //3 //@SpringBootApplication public class BootConfigurationApp { public static void main(String[] args) { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BootConfigurationApp.class); applicationContext.getBean(BootConfiguration.class).hello(); // SpringApplication.run(BootConfigurationApp.class,args); } }
1、配置扫描包
2、当@EnableConfigurationProperties注解应用到你的@Configuration时,任何被@ConfigurationProperties注解的beans将自动被Environment属性配置
3、在@ConfigurationProperties为属性赋值前加载配置文件,不可以将需要加在的配置文件写在和@ConfigurationProperties相同的位置
标签:width version bean getname group 为我 port ack path
原文地址:http://www.cnblogs.com/irich/p/7488998.html