SpringBoot之注解

@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定义方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

万码无虫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值