1.@springbootapplication
包含@Configuration、@CommentScan、@EnableAutoConfiguration
@Configuration 使用java 代码的方式实现spring中配置xml的效果
指出该类是 Bean 配置的信息源,相当于XML中的<beans></beans>,一般加在主类上。
@Bean:
相当于XML中的<bean></bean>,放在方法的上面,而不是类,意思是产生一个bean,并交给spring管理。
1.通过java代码注册bean
@Configuration
public class TestMybaitsConf {
@Bean
public DataSource dataSource() {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://192.168.100.25:6660/TXSMS?useUnicode=true&characterEncoding=utf-8");
dataSource.setUser("root");
dataSource.setPassword("123456");
} catch (Exception e) {
throw new RuntimeException(e);
}
return dataSource;
}
}
2.使用XML 配置
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://192.168.100.25:6660/TXSMS? useUnicode=true&characterEncoding=utf-8"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
3.使用xml 注册bin
@Configuration
@ImportResource("classpath:spring-mybatis.xml")
@ComponentScan
组件扫描。个人理解相当于<context:component-scan>,如果扫描到有@Component @Controller @Service等这些注解的类,则把这些类注册为bean。
@EnableAutoConfiguration
总结
从classpath中搜索所有META-INF/spring.factories配置文件然后,将其中org.springframework.boot.autoconfigure.EnableAutoConfiguration key对应的配置项加载到spring容器
只有spring.boot.enableautoconfiguration为true(默认为true)的时候,才启用自动配置
@EnableAutoConfiguration还可以进行排除,排除方式有2中,一是根据class来排除(exclude),二是根据class name(excludeName)来排除
其内部实现的关键点有
1)ImportSelector 该接口的方法的返回值都会被纳入到spring容器管理中
2)SpringFactoriesLoader 该类可以从classpath中搜索所有META-INF/spring.factories配置文件,并读取配置
@RestController
包含 @Controller, 和@Responebody 注解
@AutoWired:
byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。
当加上(required=false)时,就算找不到bean也不报错。
全局异常处理
@ControllerAdvice:
包含@Component。可以被扫描到。
统一处理异常。
@ExceptionHandler(Exception.class):
用在方法上面表示遇到这个异常就执行以下方法。
本文深入探讨Spring Boot中的关键注解,如@SpringBootApplication、@Configuration、@Bean、@ComponentScan、@EnableAutoConfiguration、@RestController和@AutoWired的使用与作用,以及全局异常处理的实现。
647

被折叠的 条评论
为什么被折叠?



