Fork me on GitHub

spring注解大全解析

@Service用于标注业务层组件

@Controller用于标注控制层组件(如struts中的action)

@Repository用于标注数据访问组件,即DAO组件

@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

@Autowired后不需要getter()和setter()方法,Spring也会自动注入。

在接口前面标上@Autowired注释使得接口可以被容器注入,如:

1
2
3
@Autowired  
@Qualifier("chinese")
private Man man;

当接口存在两个实现类的时候必须使用@Qualifier指定注入哪个实现类,否则可以省略,只写@Autowired。
使用@Autowired时你的OrganDaoIbatis 必须以@Service或@Component注解才行。

之前用户使用的是3个注解注解他们的main类。分别是@Configuration,@EnableAutoConfiguration,@ComponentScan。由于这些注解一般都是一起使用,spring boot提供了一个统一的注解@SpringBootApplication。
@SpringBootApplication = (默认属性)@Configuration + @EnableAutoConfiguration + @ComponentScan
1、@Configuration
提到@Configuration就要提到他的搭档@Bean。使用这两个注解就可以创建一个简单的spring配置类,可以用来替代相应的xml配置文件。
派生到我的代码片

1
2
3
4
5
6
<beans>  
<bean id = "car" class="com.test.Car">
<property name="wheel" ref = "wheel"></property>
</bean>
<bean id = "wheel" class="com.test.Wheel"></bean>
</beans>

相当于:
派生到我的代码片

1
2
3
4
5
6
7
8
9
10
11
12
13
@Configuration  
public class Conf {
@Bean
public Car car() {
Car car = new Car();
car.setWheel(wheel());
return car;
}
@Bean
public Wheel wheel() {
return new Wheel();
}
}

1、@Configuration
注解类标识这个类可以使用Spring IoC容器作为bean定义的来源。@Bean注解告诉Spring,一个带有@Bean的注解方法将返回一个对象,该对象应该被注册为在Spring应用程序上下文中的bean。

2、@EnableAutoConfiguration
能够自动配置spring的上下文,试图猜测和配置你想要的bean类,通常会自动根据你的类路径和你的bean定义自动配置。

3、@ComponentScan
会自动扫描指定包下的全部标有@Component的类,并注册成bean,当然包括@Component下的子注解@Service,@Repository,@Controller。

4、@ResponseBody
用该注解修饰的函数,会将结果直接填充到HTTP的响应体中,一般用于构建RESTful的api;

5、@Controller
用于定义控制器类,在spring 项目中由控制器负责将用户发来的URL请求转发到对应的服务接口(service层)。

6、@RestController
@ResponseBody和@Controller的合集

7、@RequestMapping
提供路由信息,负责URL到Controller中的具体函数的映射。

8、@EnableAutoConfiguration
Spring Boot自动配置(auto-configuration):尝试根据你添加的jar依赖自动配置你的Spring应用。例如,如果你的classpath下存在HSQLDB,并且你没有手动配置任何数据库连接beans,那么我们将自动配置一个内存型(in-memory)数据库”。你可以将@EnableAutoConfiguration或者@SpringBootApplication注解添加到一个@Configuration类上来选择自动配置。如果发现应用了你不想要的特定自动配置类,你可以使用@EnableAutoConfiguration注解的排除属性来禁用它们。

9、@ComponentScan
表示将该类自动发现(扫描)并注册为Bean,可以自动收集所有的Spring组件,包括@Configuration类。我们经常使用@ComponentScan注解搜索beans,并结合@Autowired注解导入。

10、@Configuration
相当于传统的xml配置文件,如果有些第三方库需要用到xml文件,建议仍然通过@Configuration类作为项目的配置主类——可以使用@ImportResource注解加载xml配置文件。

11、@SpringBootApplication
相当于@EnableAutoConfiguration、@ComponentScan和@Configuration的合集。

12、@Import
用来导入其他配置类。

13、@ImportResource
用来加载xml配置文件。

14、@Autowired
自动导入依赖的bean

15、@Service
一般用于修饰service层的组件

16、@Repository
使用@Repository注解可以确保DAO或者repositories提供异常转译,这个注解修饰的DAO或者repositories类会被ComponetScan发现并配置,同时也不需要为它们提供XML配置项

17、@MapperScan
使用mybatis注解需要的配置。如下面的代码所示,使用@MapperScan来扫描注册mybatis数据库接口类,其中basePackages属性表明接口类所在的包,sqlSessionTemplateRef表明接口类使用的SqlSessionTemplate。如果项目需要配置两个数据库,@MapperScan也需要分别配置。

相关文章

微信打赏

赞赏是不耍流氓的鼓励

评论系统未开启,无法评论!