springboot 常用注解

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&amp;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&amp;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):
用在方法上面表示遇到这个异常就执行以下方法。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值