@Configuration
@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,并用于构建bean定义,初始化Spring容器。
@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的<beans>
,作用为:配置spring容器(应用上下文)
如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false">
</beans>
而在被@Configuration标注在类里边,被标注@Bean的每个方法其实就是<beans> </beans>里边的定义的各种<bean></bean>
如下实例:
@Configuration
//@EnableConfigurationProperties(HelloServiceProperties.class)
public class HelloServiceAutoConfiguration {
public HelloServiceAutoConfiguration() {
System.out.println("TestConfiguration容器启动初始化。。。");
}
@Bean
public HelloServiceProperties str() {
System.out.println("HelloServiceProperties类进行初始化");
return new HelloServiceProperties();
}
}
在该实例中,我们观察程序在启动的时候,控制台的输出中就有程序中的两句话,说明程序在启动的时候就在加载这个类,相当于spring中的xml配置文件。
如果我们想把配置文件(Application.properties)的信息,读取并自动封装成实体类,这样子,我们在代码里面使用就轻松方便多了,这时候,我们就可以使用@ConfigurationProperties,它可以把同类的配置信息自动封装成实体类
//@Component
@ConfigurationProperties(prefix = "haoab")
public class HelloServiceProperties {
/*
* @Value("${hello}")这种方式可以获取配置文件中的值
*/
//@Value("${hello}")
private String port;
//@Value("${two}")
private String name ;
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
所用到的配置文件如图:
我们在controller中可以测试下用配置文件中初始化的实体类
@RestController
@Api(value="配置测试")
public class ConfigutionTestController {
@Autowired
private HelloServiceProperties helloServiceProperties;
@ApiOperation(notes="查询预置属性值", value = "查询预置属性值")
@RequestMapping(value="/getContext",method=RequestMethod.GET)
public String getVoid(){
return helloServiceProperties.getName();
}
}
最终输出结果