文章目录
@EnableConfigurationProperties
@EnableConfigurationProperties(属性读取类.class)
@EnableConfigurationProperties 注解的作用是:让使用了 @ConfigurationProperties 注解的类生效,并且将该类注入到 IOC 容器中,交由 IOC 容器进行管理。
@Service
@EnableConfigurationProperties(MyConfigurationProperties.class)
public class HelloServiceImpl implements HelloService {
}
有了 @EnableConfigurationProperties 注解之后该实体类就不需要加上 @Component 注解了。
@ConfigurationProperties
@ConfigurationProperties(prefix=“jdbc”)
springboot的注解,可以读取springboot的application的配置文件。
//jdbc配置信息属性类
@Component
@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
private String driverClassName;
private String url;
private String username;
private String password;
}
- @ConfigurationProperties注解可以生效是因为在SpringBoot中有一个类叫ConfigurationPropertiesAutoConfiguration,它为@ConfigurationProperties注解的解析提供了支持的工作。
- 但如果一个类只配置了 @ConfigurationProperties 注解,而没有使用 @Component 注解将该类加入到 IOC 容器中,那么它就不能完成读取 xxx.properties 配置文件,不能完成 Java Bean 的数据绑定。
JDBC使用用例
创建配置类(config/JdbcConfiguration)
//数据源的jdbc配置类
@Configuration
public class JdbcConfiguration {
@Bean
@ConfigurationProperties(prefix = "jdbc")
public DataSource getDataSource(){
DruidDataSource source = new DruidDataSource();
return source;
}
}
编写application.properties
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
@ResponseBody
一般在异步获取数据时使用,在使用 @RequestMapping 后,返回值通常解析为跳转路径,加上 @Responsebody 后返回结果不会被解析为跳转路径,而是直接写入 HTTP response body 中。
@RestController
public class HelloController {
@Autowired
private MyConfigurationProperties config;
@GetMapping("/config")
private String testConfigurationProperties(){
System.out.println(config);
return "SUCCESS!!!";
}
}
@GetMapping
@RestController
@RestController相当于@ResponseBody+@Controller合在一起使用。
@SpringBootApplication
//相当于@enableAutoConfiguration ComponentScan SpringBootConfiguration的组合
ComponentScan扫描位置
@ComponentScan
通过注解指定spring在创建容器时要扫描的包
o属性,value或者basePackages
等同于下面,路径是个类路径,理论上应该是{“cn.xaut”},省略了
@EnableAutoConfiguration
@EnableAutoConfiguration可以帮助SpringBoot应用将所有符合条件的@Configuration配置都加载到当前SpringBoot创建并使用的IoC容器。
它包含了Import:用于导入其他的配置类。
如自动注入
@SpringBootConfiguration
根据Spring文档,@ SpringBootConfiguration只是Spring标准@Configuration批注的替代方法。 两者之间的唯一区别是@SpringBootConfiguration允许自动找到配置。使用@SpringBootConfiguration标记一个类时,这意味着该类提供了@Bean定义方法。