springboot的最强大的就是那些xxxAutoconfiguration,可是这些xxxAutoConfiguration又依赖那些starter,只有导入了这些场景启动器(starter),咱们不少自动配置类才能有用,而且还会新增一些功能。java
咱们要用一个场景(好比web),直接导入下面所示的依赖,可是在jar包里面去看这个,你会发现里面只有一些基本的配置文件,什么类都没有,就可以想到这个一类就相似一个公司前台的做用,经过这个公司前台,可以联系到公司内部。web
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
@Data @ConfigurationProperties(prefix = "db.hello") //配置文件的前缀 public class HelloProperties { private String before; private String after; }
@ConfigurationProperties
类型安全的属性注入,即将 application.properties 文件中前缀为 "db.hello"的属性注入到这个类对应的属性上此时这个类和properties类还没什么关系,必需要让第三方传入properties spring
@Data public class HelloWorld { private HelloProperties properties; public String sayHelloWorld(String name) { return properties.getBefore() + ":" + name + "," + properties.getAfter(); } }
@Configuration //配置类 @ConditionalOnWebApplication //判断当前是web环境 @EnableConfigurationProperties(HelloProperties.class) //向容器里导入HelloProperties public class HelloWorldAutoConfiguration { @Autowired HelloProperties properties; //从容器中获取HelloProperties组件 /** * 从容器里得到的组件传给HelloWorld,而后再将 * HelloWorld组件丢到容器里 * @return */ @Bean public HelloWorld helloWorld() { HelloWorld helloWorld = new HelloWorld(); helloWorld.setProperties(properties); return helloWorld; } }
作完这一步以后,咱们的自动化配置类就算是完成了浏览器
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ cn.n3.db.HelloWorldAutoConfiguration
@Controller public class TestController { @Autowired HelloWorld helloWorld; @RequestMapping("/hello") @ResponseBody public String sayHello() { return helloWorld.sayHelloWorld("test"); } }