`
raymond.chen
  • 浏览: 1433468 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Spring注解类的整理

阅读更多

二、Spring内置注解

     1、@Component注解

          @Component("Bean的名称")  通过注解标注一个类为受管Bean。默认情况下通过@Component定义的Bean都是singleton的,如果需要使用其它作用范围的Bean,可以通过@Scope注释来达到目标。

 

      注解类层次关系:

          @Component

                  @Configuration

                  @Controller

                          @RestController

                  @Service

                  @Repository

 

     2、@Service注解

          用于标注业务层组件

 

     3、@Repository注解

          用于标注数据访问组件

 

     4、@Autowired注解

          默认按类型装配bean,且容器中匹配的候选Bean数目必须有且仅有一个,可以设置required=false让其成为可选的。想使用名称装配可以结合@Qualifier注解进行使用。

 

           @Qualifier注解

                   @Qualifier("Bean的名称")  指定注入Bean的名称。只能用于类的成员变量、方法的参数和构造子的参数。如果它与@Autowired联合使用,则自动装配的策略就变为byName了。

 

     注解使用范例:

public class Person {
	private Long id;
	private String name;
	private Address address;
	
	public Person(){
		
	}
	
	public Person(Long id, String name){
		this.id = id;
		this.name = name;
	}

	@Autowired(required=false)
	public void setAddress(@Qualifier("address2")Address address) {
		this.address = address;
	}
}

 

<!-- 通过注解定义bean。默认同时也通过注解自动注入 -->
<context:component-scan base-package="com.cjm"/>

<bean id="address1" class="com.cjm.model.Address" p:city="gz1" p:zipCode="111"/>
<bean id="address2" class="com.cjm.model.Address" p:city="gz2" p:zipCode="222"/>

<bean id="person" class="com.cjm.model.Person">
	<constructor-arg index="0" value="111"/>
	<constructor-arg index="1" value="cjm"/>
</bean>

 

     自定义限定符注解:

@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface MyQulifier {
	String value();
}

 

public class Person {
	private Long id;
	private String name;
	private Address address;
	
	public Person(){
		
	}
	
	public Person(Long id, String name){
		this.id = id;
		this.name = name;
	}

	@Autowired
	public void setAddress(@MyQulifier("a2")Address address) {
		this.address = address;
	}
}

 

<bean id="address1" class="com.cjm.model.Address" p:city="gz1" p:zipCode="111">
	<qualifier type="com.cjm.annotation.MyQulifier" value="a1"/>
</bean>

<bean id="address2" class="com.cjm.model.Address" p:city="gz2" p:zipCode="222">
	<qualifier type="com.cjm.annotation.MyQulifier" value="a2"/>
</bean>

 

     5、@ComponentScan

          该注解默认会自动扫描该类所在包下所有的配置类,相当于之前的 <context:component-scan>。

          useDefaultFilters属性的默认值为true,也就是说spring默认会自动发现被 @Component、@Controller、@Service和@Repository 标注的类,并注册进容器中。

 

          可以使用value属性来指定要扫描的包。

                  @ComponentScan(value="com.seasy.controller")

 

          使用 excludeFilters 来按照规则排除某些包的扫描。

                 @ComponentScan(value="com.seasy", excludeFilters={@Filter(type=FilterType.ANNOTATION, value={Controller.class})}, useDefaultFilters=false)

 

          使用 includeFilters 来按照规则只包含某些包的扫描。

                @ComponentScan(value="com.seasy", includeFilters={@Filter(type=FilterType.ANNOTATION, classes={Controller.class})}, useDefaultFilters=false)

 

          添加多种扫描规则

                  可以使用 @ComponentScans 来添加多个 @ComponentScan,从而实现添加多个扫描规则。同样,也需要加上 @Configuration 注解,否则无效。

                 

                  @ComponentScans(value={@ComponentScan(value="com.seasy.controller"), @ComponentScan(value="com.seasy.service")})

                  @Configuration

                  public class BeanConfig {    }

 

     6、@Scope注解

          @Scope("Bean的作用范围")  通过@Scope注解为受管bean指定作用域。Bean的作用范围有:singleton、prototype、request、session、globalsession等。

 

     7、@ImportResource

           导入Spring的xml配置文件,让配置文件的内容生效,同时需要配合@Configuration注解一起使用:

          @Configuration

          @ImportResource("classpath:/com/acme/properties-config.xml")

          public class AppConfig{

                   

          }

 

     8、@PropertySource

          加载指定的属性文件,文件中的属性可以配合@value注解一起使用

          @PropertySource("classpath:person.properties")

          public class AppConfig{

                 @value("${key}")

                 private String username;

                

          }

 

       9、@Value

              通过@Value将外部的值动态注入到Bean中

 

              @Value的值有两类:

                     ${ property : default_value }注入的是外部参数对应的property

                     #{ obj.property? : default_value }注入的是SpEL表达式对应的内容

 

              注入普通字符串

                     @Value("normal")

                     private String normal;

 

              //注入文件资源

                     @Value("classpath:com/seasy/config/config.txt")

                     private Resource resourceFile;

 

              //注入URL资源

                     @Value("http://www.baidu.com")

                     private Resource testUrl;

 

              //注入操作系统属性

                     @Value("#{systemProperties['os.name']}")

                     private String systemPropertiesName;

 

              //注入表达式结果,T表示使用类的静态方法

                     @Value("#{ T(java.lang.Math).random() * 100.0 }")

                     private double randomNumber;

 

              //注入其他Bean属性

                     @Value("#{beanInject.another}")

                     private String fromAnotherBean;

 

              //将外部配置文件的值动态注入到Bean中。

              //在Springboot中默认可以使用application.properties属性文件的配置,自定义属性文件可以通过@PropertySource加载

                     @Value("${app.name}")

                     private String appName;

 

      10、@Required

             该注解适用于bean属性的setter方法,并表示bean属性必须要设值。否则,容器会抛出一个BeanInitializationException异常。

 

             @Required

             public void setAge(Integer age) {

                    this.age = age;

             }

 

      11、@Primary

             自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常

 

      12、@DependsOn

            用于强制初始化其他Bean,可以修饰Bean类或方法。

            @DependsOn({"bean1", "bean2"})  

 

      13、@Lazy

             用于指定是否延迟初始化Bean,主要用于修饰Bean类。

             @Lazy(true) 

 

      14、@EnableAspectJAutoProxy

             启用AOP。该注解类用于自动注册AnnotationAwareAspectJAutoProxyCreator对象到Spring容器中,该对象除了会自动将容器的所有Advisor作用于所有的Bean外,也会自动将标注有@Aspect注解的切面类织入到目标bean中。

 

三、JSR规范的注解(需要common-annotations.jar包的支持)

     1、@Resource  由JSR-250提供

           作用与@Autowired注解相同。默认按名称进行装配bean,名称可以通过name属性进行指定。

          @Resource(name="person")         name属性用于指定注入的Bean的名称。

          @Resource(type=Person.class)    type属性用于指定注入的Bean的类型。

 

     2、@PostContsuct

          用于指定受管Bean的初始化方法,作用与Bean的init-method属性类似。

 

     3、@PreDestory

          用于指定受管Bean的析构方法,作用与Bean的destory-method属性类似。

 

     4、@Inject  由JSR-330提供

          和spring中的 @Autowired 相同。

 

     5、@Named

          和spring中的 @Component 相同。

          @Name可以有值,如果没有值生成的bean名称默认和类名相同。

 

 

0
1
分享到:
评论

相关推荐

    Spring 注解.xmind

    Spring注解大全,注解整理方式采用思维导图工具(XMind)整理,对注解按自己的方式进行了分类,并对所有的注解在备注中进行了解释说明;

    spring注解大全整理.docx

    Spring 注解大全整理 Spring 框架提供了许多注解,用于简化配置和编程。这些注解可以分为多个类别,包括组件扫描、依赖注入、切面编程、事务管理、缓存、异步任务和计划任务等。 一、组件扫描 * @Controller:...

    spring注解整理,及应用

    Spring 注解整理及应用 Spring 框架中提供了许多注解来简化开发过程,这些注解可以分为多个类别,如 Controller、Service、DAO 等。下面我们将对 Spring 中常用的注解进行整理和解释: 一、Controller 相关注解 *...

    Spring常用注解.xmind

    Spring 常用注解整理,分类:创建对象;注入数据;范围;全局异常;生命周期;新注解;JPA;扩展原理等注解类型。

    spring4注解[整理].pdf

    spring4注解[整理].pdf

    spring 常用注解

    自己整理的一些常见的spring注解,文件是xmind的,平时用于梳理记忆

    Spring注解.txt

    自整理spring大部分日常使用到的注解说明 自整理spring大部分日常使用到的注解说明 自整理spring大部分日常使用到的注解说明

    华为技术专家整理Spring Boot 注解大全.docx

    @ComponentScan:用于指定Spring需要扫描的包,以发现并注册@Component、@Service、@Repository和@Controller等注解的类。默认会扫描声明它的类所在的包及其子包。 @Autowired:自动装配Bean,Spring会根据类型或...

    spring4注解

    #### 二、Spring注解图示与分类 ##### 2.1 Spring-Context 模块的注解图 - **@Component**: 用于标记任何Java类作为Spring中的一个组件。该注解通常配合`&lt;context:component-scan&gt;`使用,以便Spring能够自动检测和...

    WEB开发-spring 5.0的注解与功能整理

    介绍spring 5.0中所有注解的使用和功能

    Spring笔记整理.zip

    了解和熟练使用Spring注解是提高开发效率的关键。 9. **核心包**:Spring的核心包包括`spring-context`、`spring-beans`等,它们提供了Spring的基本功能。`spring-context`包含bean的生命周期管理、事件发布、国际...

    spring知识点代码示例整理

    - `spring_aop_annotation` 文件夹包含的是使用注解方式实现的 AOP 示例。在 Spring 中,AOP 允许开发者定义“切面”,将关注点(如日志、事务管理)与业务逻辑分离。通过 @Aspect 注解定义切面,@Before、@After、...

    spring5学习代码整理文件

    这个"spring5学习代码整理文件"包含了个人在学习Spring5过程中整理的各种代码示例,旨在帮助理解和掌握Spring5的关键概念和技术。 1. **依赖注入(DI)**:Spring5通过DI来解耦应用程序组件,使得组件之间不再硬...

    java注解整理

    - `@Component`:定义了一个Spring Bean,表示这个类会被Spring容器管理。 - `@Service`:`@Component`的子注解,常用于业务逻辑层(Service层)。 - `@Repository`:`@Component`的子注解,用于数据访问层(DAO...

    个人整理的Spring、SpringMVC、MyBatis相关知识的思维导图

    * @Configuration 被此注解标注的类,会被 Spring 认为是配置类。 * @Import 在一个配置类中导入其他配置类的内容 Spring 组件扫描 * @ComponentScan 组件扫描 * @Component 普通组件 * @Service 业务逻辑层,...

    Spring_MVC 3.0整理汇总

    【Spring_MVC 3.0 整理汇总】 一、前言 Spring_MVC 3.0 是一款广泛使用的轻量级MVC框架,因其简洁的设计、强大的功能和优秀的性能,自3.0版本发布以来,深受开发者的青睐。与Struts2相比,Spring_MVC在学习曲线、...

    Spring基础学习资料,很全面,很经典,手工整理,适合刚学习spring的同学

    随着Java的发展,Spring引入了注解来替代XML配置,如`@Component`、`@Service`、`@Repository`和`@Controller`用于标记bean,`@Autowired`进行自动装配。这种方式更加简洁,减少了大量XML配置工作,使代码更易读。 ...

    【新手向】spring系列jar包整理

    【新手向】Spring系列Jar包整理是一篇针对初学者的指南,主要涵盖了Spring框架的核心组件以及与MyBatis集成的相关库。在这个压缩包中,包含了以下几个重要的Java库: 1. **spring-core-5.2.5.RELEASE.jar**: 这是...

    传智播客Spring2.5.6学习笔记最新整理

    按照“传智播客Spring2.5.6学习笔记最新整理”的指引,我们需从官方下载页面http://www.springsource.org/download下载Spring框架,随后解压缩并定位到关键的JAR文件。这些JAR文件包括: - `dist\spring.jar`:核心...

Global site tag (gtag.js) - Google Analytics