三、SpringBoot的常用注解以及解释

一、注解列表

1.@SpringBootApplication  等同于@ComponentScan+@Configuration+@EnableAutoConfiguration

2.@RestController 等同于@Controller+@ResponseBody

3.@Autowired

二、注解详解

1.@SpringBootApplication  等同于@ComponentScan+@Configuration+@EnableAutoConfiguration详解

在了解@ComponentScan之前,我们先了解下Spring,Spring是一个依赖注入(dependency injection)框架,所有的内容都是关于bean的定义及其依赖关系。定义Spring Beans的第一步是使用正确的注解@Component或@Service或@Repository或@Controller等这些注解的类,Spring就会把他们注册成为Bean。

1.1 对于@ComponentScan来说不仅可以把以上的@Component或@Service或@Repository或@Controller等这些注解的类注册成为Bean,包括带有@Configuration类。

下面举个例子:

package com.tydic.springboot.springbootdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class SpringbootDemo {

    public static void main(String[] args) {
        ApplicationContext applicationContext = 
                SpringApplication.run(SpringbootIn10StepsApplication.class, args);

        for (String name : applicationContext.getBeanDefinitionNames()) {
            System.out.println(name);
        }
    }
}

类 SpringbootDemo 在com.tydic.springboot.springbootdemo包下,这个类使用了@SpringBootApplication注解,该注解定义了Spring将自动扫描包com.tydic.springboot.springbootdemo及其子包下的带有@Service,@Repository等注解的类。

但假如你一个类定义在包com.tydic.springboot.other下,那么你的启动类和你新建的这个新包不属于同级包及其子包,这个时候我们的@ComponentScan就会起到作用了。

定义@CoponentScan(“com.tydic.springboot.other”)

这么做扫描的范围扩大到整个父包com.tydic.springboot.springbootdemo

package com.tydic.springboot.springbootdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "com.tydic.other")
@SpringBootApplication
public class SpringbootDemo {

    public static void main(String[] args) {
        ApplicationContext applicationContext = 
                SpringApplication.run(SpringbootIn10StepsApplication.class, args);

        for (String name : applicationContext.getBeanDefinitionNames()) {
            System.out.println(name);
        }
    }
}

总之一句话:ComponentScan做的事情就是告诉Spring从哪里找到bean

1.2 @Configuration  SpringBoot推荐使用java代码的形式申明注册bean,@Configuration注解可以用java代码的形式实现spring中xml配置文件配置的效果。所以@Configuration这个注解等同于spring的xml配置文件。

1.2.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://localhost/CMX?useUnicode=true&characterEncoding=utf-8");
            dataSource.setUser("root");
            dataSource.setPassword("123456");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) {
        SqlSessionFactory factory = null;
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setConfigLocation(resolver.getResource("classpath:mybatis.xml"));
        try {
            factory = bean.getObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return factory;
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

1.2.2  使用xml配置bean

@Configuration
@ImportResource("classpath:spring-mybatis.xml")
public class TestMybaitsConf {

}

spring-mybatis.xml :

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc  http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/jee  http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <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>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis.xml"></property>
    </bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactory"></constructor-arg>
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

总结:两种注册bean的效果完全一样,但springboot推荐使用1.2.1中的方式,使用java代码注册bean

1.3 @EnableAutoConfiguration 自动配置,此注释自动载入应用程序所需的所有Bean——这依赖于Spring Boot在类路径中的查           找,这个注释告诉SpringBoot“猜”你将如何想配置Spring,基于你已经添加jar依赖项。如果spring-boot-starter-web已经添加           Tomcat和Spring MVC,这个注释自动将假设您正在开发一个web应用程序并添加相应的spring设置。

2.@RestController 等同于@Controller+@ResponseBody 表示这是个控制器bean,并且是将函数的返回值直 接填入HTTP响应体中,是REST风格的控制器。

@Controller
public class User1MapperController {

    @ResponseBody
    @RequestMapping("/addUser1")
    public String addUser1(String name,Integer age){
        user1Mapper.addUser1(name,age);
        return "成功。。。。";
    }
}

等同于:

@RestController
public class User1MapperController {

    @RequestMapping("/addUser1")
    public String addUser1(String name,Integer age){
        user1Mapper.addUser1(name,age);
        return "成功。。。。";
    }
}

3.@Autowired 自动导入依赖的bean(通过@Autowired注入spring管理的bean)

@Controller
public class User1MapperController {

    @Autowired
    private User1Mapper user1Mapper;

    @Autowired
    private User2Mapper user2Mapper;

    @ResponseBody
    @RequestMapping("/addUser1")
    public String addUser1(String name,Integer age){
        user1Mapper.addUser1(name,age);
        return "成功。。。。";
    }

    @ResponseBody
    @RequestMapping("/addUser2")
    public String addUser2(String name,Integer age){
        user2Mapper.addUser2(name,age);
        return "成功。。。!!";
    }

}

Always keep the faith!!!      

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Spring Boot常用的注解解释: 1. @SpringBootApplication:这个注解是一个组合注解,包含了@Configuration、@EnableAutoConfiguration和@ComponentScan。它用于标识一个主启动类,表示这是一个Spring Boot应用程序的入口。 2. @RestController:这个注解用于标识一个类是RESTful风格的控制器,它会自动将返回的对象转换为JSON格式的响应。 3. @RequestMapping:这个注解用于映射HTTP请求到控制器的处理方法上。可以用于类级别和方法级别,用于指定URL路径和HTTP请求方法。 4. @GetMapping、@PostMapping、@PutMapping、@DeleteMapping:这些注解分别用于映射HTTP的GET、POST、PUT和DELETE请求到控制器的处理方法上。 5. @PathVariable:这个注解用于获取URL路径的参数值,并将其绑定到方法的参数上。 6. @RequestParam:这个注解用于获取请求参数的值,并将其绑定到方法的参数上。 7. @RequestBody:这个注解用于获取请求体的内容,并将其转换为方法参数的类型。 8. @ResponseBody:这个注解用于将方法的返回值转换为HTTP响应的内容。 9. @Autowired:这个注解用于自动装配依赖对象,可以用于字段、构造方法和方法上。 10. @Component:这个注解用于标识一个类是Spring的组件,会被自动扫描并注册到Spring容器。 11. @Service:这个注解用于标识一个类是业务逻辑层的组件。 12. @Repository:这个注解用于标识一个类是数据访问层的组件。 13. @Configuration:这个注解用于标识一个类是配置类,其定义了一些Bean的创建和配置。 14. @EnableAutoConfiguration:这个注解用于启用Spring Boot的自动配置机制。 15. @Conditional:这个注解用于根据条件来决定是否创建某个Bean。 16. @Value:这个注解用于从配置文件读取属性值,并将其注入到方法参数或字段。 17. @Async:这个注解用于标识一个方法是异步执行的。 18. @EnableScheduling:这个注解用于启用Spring的定时任务调度功能。 19. @EnableCaching:这个注解用于启用Spring的缓存功能。 20. @EnableSwagger2:这个注解用于启用Swagger2的API文档生成功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值