spring注解大全

一、常用注解列表

声明bean的注解
@component把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>
@controller标注为控制层(组合了@Component注解)标识一个该类是Spring MVC controller处理器,用来创建处理http请求的对象.
@service标注为服务层(组合了@Component注解)用于标注业务层组件,说白了就是加入你有一个用注解的方式把这个类注入到spring配置中
@repository标注为dao层(组合了@Component注解)实现dao[data access object]访问
注入bean的注解
@Autowired默认根据 类型(by class) 进行自动装配,Spring提供的工具(由Spring的依赖注入工具(BeanPostProcessor、BeanFactoryPostProcessor)自动注入)
@Qualifier 与@Autowired配合使用,Autowired默认是以类型注入,Qualifier 是在此基础上定义 by name来匹配
@Resource默认根据 名称(by name) 进行自动装配,JSR-250标准注解(@Resource有两个属性是比较重要的,分别是name和type,Spring将 @Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型)
@Valuevalue注解的使用有${} #{}两种方式
java配置类相关注解
@Configuration声明当前类为配置类,相当于xml形式的Spring配置(作用在类上)类似xml中的<beans> 标签
@Bean注解在方法上,声明当前方法的返回值为一个bean,替代xml中的方式(作用在方法上)等价于xml文件中的<bean> 标签
@ComponentScan用于对Component进行扫描,相当于xml中的(作用在类上)
@Import引入 @Configuration【Class<?>[] value();】
@ImportResource引入 xml文件【String[] value() default {};】
@WishlyConfiguration为@Configuration与@ComponentScan的组合注解,可以替代这两个注解
Bean的属性支持
@Scope声明当前 Bean 的作用域
@PostConstructBean 初始化后执行。由JSR-250提供,在构造函数执行完之后执行(等价于xml配置文件中bean的initMethod
@PreDestroyBean 销毁前执行。由JSR-250提供,在Bean销毁之前执行(等价于xml配置文件中bean的destroyMethod
@StepScope在Spring Batch中还有涉及
切面(AOP)相关注解
@Aspect声明一个切面(类上) 使用@After、@Before、@Around定义建言(advice),可直接将拦截规则(切点)作为参数
@After在方法执行之后执行(作用在方法上)
@Before在方法执行之前执行(作用在方法上) 
@Around 在方法执行之前与之后执行(作用在方法上)
@PointCut声明切点 在java配置类中使用@EnableAspectJAutoProxy注解开启Spring对AspectJ代理的支持(作用在类上)
  
  
  
  
异步相关
@EnableAsync配置类中,通过此注解开启对异步任务的支持,叙事性AsyncConfigurer接口(类上)
@Async在实际执行的bean方法使用该注解来申明其是一个异步任务(方法上或类上所有的方法都将异步,需要@EnableAsync开启异步任务)
测试相关注解
@RunWith运行器,Spring中通常用于对JUnit的支持,@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration用来加载配置ApplicationContext,其中classes属性用来加载配置类@ContextConfiguration(classes={TestConfig.class})
  

 

二、声明Bean的注解

我们要将一个类托管给spring容器,只需要在对应的类上加上一个@Component注解,就将该类定义为一个Bean了。

Spring还提供了更加细化的注解形式:@Repository、@Service、@Controller,它们分别对应存储层Bean,业务层Bean,和展示层Bean。目前版本(2.5)中,这些注解与@Component的语义是一样的,完全通用,在Spring以后的版本中可能会给它们追加更多的语义。所以,我们推荐使用@Repository、@Service、@Controller来替代@Component。 

spring会将声明了@Component,@Service,@Controller,@Repository注解的类纳入进spring容器中管理。 

//控制器(注入服务)
@Controller
public class UserController{...} 

//服务(注入dao)
@Service
public class UserServiceImpl implements UserService {...} 

//dao(实现dao[data access object]访问)
@Repository
public class UserDaoImpl implements UserDao {...}

//把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>
@Component
public class OtherClass{...}

1、spring默认:声明的Bean默认名称是类名(头字母小写),默认作用域是单例模式

@Service
public class UserServiceImpl implements UserService {...} 

 等值于

<bean id="userServiceImpl " class="com.XXX.UserServiceImpl" scope="singleton" />

 

2、如果想自定义可以通过如下方式来改变,改变后:

@Service("myUserService") 
@Scope("prototype")
public class UserServiceImpl implements UserService { }

 等值于

<bean id="myUserService" class="com.XXX.UserServiceImpl" scope="prototype" />

 

3、我们将类声明为Bean后,应该在xml文件中配置扫描,使spring启动时,自动扫描这些类

 我们要在配置我们类所在的包路径,通常我会配置大一点的路径,这样能包含进所有类

<context:component-scan base-package=”com.XXXX”> 

其中base-package为需要扫描的包(含所有子包) 

  1. @Service用于标注业务层组件 
  2. @Controller用于标注控制层组件(如struts中的action) 
  3. @Repository用于标注数据访问组件,即DAO组件. 
  4. @Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。    

 

三、注入Bean的注解

1、@Autowired注解(不推荐使用,建议使用@Resource)

@Autowired可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作。@Autowired的标注位置不同,它们都会在Spring在初始化这个bean时,自动装配这个属性。要使@Autowired能够工作,还需要在配置文件中加入以下

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

 2、@Qualifier注解

 @Autowired是根据类型进行自动装配的。例如,如果当Spring上下文中存在不止一个UserDao类型的bean时,就会抛出BeanCreationException异常;如果Spring上下文中不存在UserDao类型的bean,也会抛出BeanCreationException异常。我们可以使用@Qualifier配合@Autowired来解决这些问题。如下:

 1). 可能存在多个UserDao实例

加在全局变量上 

@Autowired       
@Qualifier("userServiceImpl")         
public IUserService userService;

或者,加在set方法上

@Autowired       
public void setUserDao(@Qualifier("userDao") UserDao userDao) {        
    this.userDao = userDao;        
} 

这样,Spring会找到id为userServiceImpl和userDao的bean进行装配

2). 可能不存在UserDao实例

@Autowired(required = false)        
public IUserService userService;

3. @Resource注解

JSR-250标准注解,推荐使用它来代替Spring专有的@Autowired注解。@Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按byName自动注入罢了。@Resource有两个属性是比较重要的,分别是name和type,Spring将 @Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。要使@Autowired能够工作,还需要在配置文件中加入以下:

<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />

@Resource装配顺序:

  1. 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
  2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
  3. 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
  4. 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配(见2);如果没有匹配,则回退为一个原始类型(UserDao)进行匹配,如果匹配则自动装配;

 

4、@Autowired与@Resource的区别

@Autowired与@Resource都可以用来装配bean. 都可以写在字段上,或写在setter方法上

(1)@Autowired默认按类型装配(这个注解是属业spring的)

默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false,如:@Autowired(required=false) ,如果我们想使用名称装配可以结合@Qualifier注解进行使用,如下: 

@Autowired() @Qualifier("baseDao")     
private BaseDao baseDao;    

(2)@Resource(这个注解属于J2EE的)

默认安照名称进行装配,名称可以通过name属性进行指定, 
如果没有指定name属性,当注解写在字段上时,默认取字段名进行按照名称查找,如果注解写在setter方法上默认取属性名进行装配。 当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。

@Resource(name="baseDao")     
private BaseDao baseDao; 

在java代码中可以使用@Autowire或者@Resource注解方式进行装配,这两个注解的区别是:

 

  • @Autowire 默认按照类型装配:默认情况下它要求依赖对象必须存在如果允许为null,可以设置它required属性为false,如果我们想使用按照名称装配,可 以结合@Qualifier注解一起使用;
  • @Resource默认按照名称装配:当找不到与名称匹配的bean才会按照类型装配,可以通过name属性指定,如果没有指定name属 性,当注解标注在字段上,即默认取字段的名称作为bean名称寻找依赖对象,当注解标注在属性的setter方法上,即默认取属性名作为bean名称寻找 依赖对象.

 

5、@Value

value注解的使用有${} #{}两种方式:

  • @Value(“${}”):可以获取对应属性文件中定义的属性值
  • @Value(“#{}”):表示SpEl表达式通常用来获取bean的属性,或者调用bean的某个方法。当然还有可以表示常量

配置

(1) @Value("#{configProperties['key']}")使用

配置文件

配置方法1:
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
            <value>classpath:value.properties</value>
        </list>
    </property>
</bean>
配置方法2:
<util:properties id="configProperties" location="classpath:value.properties"></util:properties>

注:配置1和配置2等价,这种方法需要util标签,要引入util的xsd:

http://www.springframework.org/schema/util

http://www.springframework.org/schema/util/spring-util-3.0.xsd"

value.properties

key=1

ValueDemo.java

@Component
public class ValueDemo {
    @Value("#{configProperties['key']}")
    private String value;
 
    public String getValue() {
        return value;
    }
}

 

(2)@Value("${key}")使用

方法一:配置文件(在上面的配置文件基础上增加)

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
    <property name="properties" ref="configProperties"/>
</bean>

方法二:直接指定配置文件,完整的配置:

<bean id="appProperty"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <array>
            <value>classpath:value.properties</value>
        </array>
    </property>
</bean>

ValueDemo.java

@Component
public class ValueDemo {
    @Value("${key}")
    private String value;
 
    public String getValue() {
        return value;
    }
}

 

(3)不通过配置文件的注入属性的情况

通过@Value将外部的值动态注入到Bean中,使用的情况有:

  • 注入普通字符串
  • 注入操作系统属性
  • 注入表达式结果
  • 注入其他Bean属性:注入beanInject对象的属性another
  • 注入文件资源
  • 注入URL资源
    @Value("normal")
    private String normal; // 注入普通字符串

    @Value("#{systemProperties['os.name']}")
    private String systemPropertiesName; // 注入操作系统属性

    @Value("#{ T(java.lang.Math).random() * 100.0 }")
    private double randomNumber; //注入表达式结果

    @Value("#{beanInject.another}")
    private String fromAnotherBean; // 注入其他Bean属性:注入beanInject对象的属性another,类具体定义见下面

    @Value("classpath:com/hry/spring/configinject/config.txt")
    private Resource resourceFile; // 注入文件资源

    @Value("http://www.baidu.com")
    private Resource testUrl; // 注入URL资源

注入其他Bean属性:注入beanInject对象的属性another

@Component
public class BeanInject {
    @Value("其他Bean的属性")
    private String another;

    public String getAnother() {
        return another;
    }

    public void setAnother(String another) {
        this.another = another;
    }
}

 

(4) 通过配置文件的注入属性的情况

通过@Value将外部配置文件的值动态注入到Bean中。配置文件主要有两类:

  • application.properties。application.properties在spring boot启动时默认加载此文件
  • 自定义属性文件。自定义属性文件通过@PropertySource加载。@PropertySource可以同时加载多个文件,也可以加载单个文件。如果相同第一个属性文件和第二属性文件存在相同key,则最后一个属性文件里的key启作用。加载文件的路径也可以配置变量,如下文的${anotherfile.configinject},此值定义在第一个属性文件config.properties

第一个属性文件config.properties内容如下: 
${anotherfile.configinject}作为第二个属性文件加载路径的变量值

book.name=bookName
anotherfile.configinject=placeholder

第二个属性文件config_placeholder.properties内容如下:

book.name.placeholder=bookNamePlaceholder

下面通过@Value(“${app.name}”)语法将属性文件的值注入bean属性值,详细代码见:

@Component
// 引入外部配置文件组:${app.configinject}的值来自config.properties。
// 如果相同
@PropertySource({"classpath:com/hry/spring/configinject/config.properties",
    "classpath:com/hry/spring/configinject/config_${anotherfile.configinject}.properties"})
public class ConfigurationFileInject{
    @Value("${app.name}")
    private String appName; // 这里的值来自application.properties,spring boot启动时默认加载此文件

    @Value("${book.name}")
    private String bookName; // 注入第一个配置外部文件属性

    @Value("${book.name.placeholder}")
    private String bookNamePlaceholder; // 注入第二个配置外部文件属性

    @Autowired
    private Environment env;  // 注入环境变量对象,存储注入的属性值

    public String toString(){
        StringBuilder sb = new StringBuilder();
        sb.append("bookName=").append(bookName).append("\r\n")
        .append("bookNamePlaceholder=").append(bookNamePlaceholder).append("\r\n")
        .append("appName=").append(appName).append("\r\n")
        .append("env=").append(env).append("\r\n")
        // 从eniroment中获取属性值
        .append("env=").append(env.getProperty("book.name.placeholder")).append("\r\n");
        return sb.toString();
    }   
}

 

四、Java配置类相关注解

1、@Configuration、@Bean

@Configuration告诉spring容器,这是一个配置类(类似xml中的 <beans> 标签)
@Bean跟 @Configuration 配合使用,标注在方法上,返回某个实例的方法(实例化一个bean),默认以方法名称做bean的id,可以指定别名,初始化方法和销毁方法(等价于spring的xml配置文件中的 <bean> 标签)作用为:注册bean对象

这是Bean的源码,可以看出一下

  • value,name属性:默认情况下,注入的bean实例,是以方法名称,作为bean的注入id,也可以通过@Bean注解里的name或者value指定名称,另外name和value都是数组,表示可以取多个名字
  • autowire属性:这个是指自动装配时候的引用,xml中,也有这个属性,默认就是NO,这个是spring的自动装配里的规则
  • initMethod,destroyMethod 属性:是指定bean的初始化方法,以及销毁方法 如下,我们在需要被注入的Person对象中,加init(),detory()方法,
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {
    @AliasFor("name")
    String[] value() default {};
 
    @AliasFor("value")
    String[] name() default {};
 
    Autowire autowire() default Autowire.NO;
 
    String initMethod() default "";
 
    String destroyMethod() default AbstractBeanDefinition.INFER_METHOD;
}

 

使用案例:

创建一个工程,引入spring的基础包

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>4.3.12.RELEASE</version>
</dependency>

创建一个基础的测试对象

package com.badger.spring.bean;
 
public class Person {
    private String name;
 
    private int age;
 
    public Person() {
        super();
    }
    public Person(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public void start() {
        System.out.println("TestBean 初始化。。。");
    }

    public void cleanUp() {
        System.out.println("TestBean 销毁。。。");
    }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
 
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}

首先,在spring 4.x之前的版本中,我们对于bean的注入方式是通过xml文件的形式配置的,如下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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
 
    <bean id="person" class="com.badger.spring.bean.Person">
        <property name="age" value="18"></property>
        <property name="name" value="xiali"></property>
    </bean>
</beans>

spring4.x之后,支持了注解式编程,如下配置

package com.badger.spring.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.badger.spring.bean.Person;
 
@Configuration
public class MyConfig {
    /**
    * 给容器中注册一个Bean;类型为返回值的类型,id默认是用方法名作为id
    * @Bean注解注册bean,同时可以指定初始化和销毁方法
    * @Bean(name="person",initMethod="init",destroyMethod="detory")
    */
    @Bean(initMethod = "start", destroyMethod = "cleanUp")
    public Person person() {
        return new Person("xiaoli", 20);
    }
}

启动类引用

@SpringBootApplication
@Import(value = {MyConfig.class})
public class Application {
 
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

 

2、@ComponentScan

 主要就是定义扫描的路径从中找出标识了需要装配的类自动装配到spring的bean容器中

做过web开发的同学一定都有用过@Controller,@Service,@Repository注解,查看其源码你会发现,他们中有一个共同的注解@Component,没错@ComponentScan注解默认就会装配标识了@Controller,@Service,@Repository,@Component注解的类到spring容器中

案例:

(1)我们一般开发都会有以下几个类

package com.marvin.controller;
import org.springframework.stereotype.Controller;
@Controller
public class UserController {
}

//---------------------------------

package com.marvin.service;
import org.springframework.stereotype.Service;
@Service
public class UserService {
}

//---------------------------------

package com.marvin.dao;
import org.springframework.stereotype.Repository;
@Repository
public class UserDao {
}

然后我们创建一个配置类,进行测试

package com.marvin.demo;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * 主配置类  包扫描com.marvin
 */
@ComponentScan(value="com.marvin")
@Configuration
public class TestComponetScan {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext2 = new AnnotationConfigApplicationContext(TestComponetScan.class);
        String[] definitionNames = applicationContext2.getBeanDefinitionNames();
        System.out.println("=================");
        for(String name : definitionNames){
            System.out.println(name);
        }
    }
}

结果如下:

userController
userDao
userService 

(2)还可以通过配合 basePackageClasses 属性来在value基础上,添加特定的某些类扫描

@ComponentScan( value = "com.marvin", basePackageClasses = UserService.class )

@ComponentScan(value="com.marvin",basePackageClasses=UserService.class)
@Configuration
public class TestComponetScan {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext2 = new AnnotationConfigApplicationContext(TestComponetScan.class);
        String[] definitionNames = applicationContext2.getBeanDefinitionNames();
        System.out.println("=================");
        for(String name : definitionNames){
            System.out.println(name);
        }
    }
}

 

3、@Bean的属性支持

bean的支持主要包含一下

  • @Scope:声明当前 Bean 的作用域
  • @PostConstruct: 等价于xml配置文件中 bean 的 initMethod
  • @PreDestroy:等价于xml配置文件中 bean 的 destroyMethod

(1)@Scope注解

Scope,也称作用域,在 Spring IoC 容器是指其创建的 Bean 对象相对于其他 Bean 对象的请求可见范围。在 Spring IoC 容器中具有以下几种作用域:基本作用域(singleton、prototype),Web 作用域(reqeust、session、globalsession),自定义作用域。 

基本作用域singleton单例模式,在整个Spring IoC容器中,使用singleton定义的Bean将只有一个实例
prototype原型模式,每次通过容器的getBean方法获取prototype定义的Bean时,都将产生一个新的Bean实例
Web 作用域request对于每次HTTP请求,使用request定义的Bean都将产生一个新实例,即每次HTTP请求将会产生不同的Bean实例。只有在Web应用中使用Spring时,该作用域才有效
session对于每次HTTP Session,使用session定义的Bean豆浆产生一个新实例。同样只有在Web应用中使用Spring时,该作用域才有效
globalsession每个全局的HTTP Session,使用session定义的Bean都将产生一个新实例。典型情况下,仅在使用portlet context的时候有效。同样只有在Web应用中使用Spring时,该作用域才有效

 我们可以通过两种方式为Bean装配scope
1.通过xml文件

<!-- 具体的作用域需要在 scope 属性中定义 -->
<bean id="XXX" class="com.XXX.XXXXX" scope="XXXX" />

2.通过注解方式文件

@Scope("session")        
@Component()        
public class UserSessionBean implements Serializable{      
 ... ...     
}  

其中比较常用的是 singleton 和 prototype 两种作用域。

  1. 对于singleton作用域的Bean,每次请求该Bean都将获得相同的实例。容器负责跟踪Bean实例的状态,负责维护Bean实例的生命周期行为;
  2. 如果一个Bean被设置成prototype作用域,程序每次请求该id的Bean,Spring都会新建一个Bean实例,然后返回给程序。在这种情况下,Spring容器仅仅使用new 关键字创建Bean实例,一旦创建成功,容器不在跟踪实例,也不会维护Bean实例的状态。

  如果不指定Bean的作用域,Spring默认使用singleton作用域。Java在创建Java实例时,需要进行内存申请;销毁实例时,需要完成垃圾回收,这些工作都会导致系统开销的增加。因此,prototype作用域Bean的创建、销毁代价比较大。而singleton作用域的Bean实例一旦创建成功,可以重复使用。因此,除非必要,否则尽量避免将Bean被设置成prototype作用域。 
   基于注解开发时,@scope完成bean的作用域配置默认是单例模式(singleton)如果需要设置的话可以修改对应值与以上提到的一致例如:@scope(“prototype”)

 

(2)@PostConstruct(JSR-250)注解

在方法上加上注解@PostConstruct,这个方法就会在Bean初始化之后被Spring容器执行(注:Bean初始化包括,实例化Bean,并装配Bean的属性(依赖注入))。它的一个典型的应用场景是,当你需要往Bean里注入一个其父类中定义的属性,而你又无法复写父类的属性或属性的setter方法时,如:

public class UserDaoImpl extends HibernateDaoSupport implements UserDao {        
    private SessionFactory mySessionFacotry;        
    
    @Resource    
    public void setMySessionFacotry(SessionFactory sessionFacotry)     
    {        
        this.mySessionFacotry = sessionFacotry;        
    }        
    
    @PostConstruct       
    public void injectSessionFactory()     
    {        
        super.setSessionFactory(mySessionFacotry);        
    }     
}  

这里通过@PostConstruct,为UserDaoImpl的父类里定义的一个sessionFactory私有属性,注入了我们自己定义的 sessionFactory(父类的setSessionFactory方法为final,不可复写),之后我们就可以通过调用 super.getSessionFactory()来访问该属性了。

 

(3)@PreDestroy(JSR-250)注解

在方法上加上注解@PreDestroy,这个方法就会在Bean初始化之后被Spring容器执行。其用法同@PostConstruct。和@PostConstruct 区别在于:@PostConstruct注释的方法将在类实例化后调用,而标注了 @PreDestroy 的方法将在类销毁之前调用。

 

4、@Import、@ImportResource

启动类中,可以通过 @Import 注解来引入我们自定义的 配置类 @Configuration

@Import :引入 @Configuration【Class<?>[] value();】

@ImportResource :引入 xml文件【String[] value() default {};】

@SpringBootApplication
@Import({
        RedisConfig.class,
        MysqlConfig.class
})
@ImportResource(value = {"classpath:beans3.xml"})
public class Application {
 
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
 
}

RedisConfig

@Configuration
@ComponentScan({"net.core.cache.redis"})
public class RedisConfig {
    public RedisConfig() {
    }
 
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new FastJson2JsonRedisSerializer(Object.class));
        return template;
    }
}

MysqlConfig 

@Configuration
@ImportResource(value = {
        "classpath:beans1.xml",
        "classpath:beans2.xml"
})
@EnableConfigurationProperties({MysqlProperties.class})
public class MysqlConfig {
    public MysqlConfig() {
    }
 
    @Bean
    DataSource dataSource(MysqlProperties mysqlProperties) {
        DruidDataSource dataSource = new DruidDataSource();
        ......
        return dataSource;
    }
}

 

 

五、配置启用注解(注意以下配置需要使用spring2.5的头文件,在spring3.0中不适用)

1.使用简化配置

Spring2.1添加了一个新的context的Schema命名空间,该命名空间对注释驱动、属性文件引入、加载期织入等功能提供了便捷的配置。我们知道注释本身是不会做任何事情的,它仅提供元数据信息。要使元数据信息真正起作用,必须让负责处理这些元数据的处理器工作起来。

AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor就是处理这些注释元数据的处理器。但是直接在Spring配置文件中定义这些Bean显得比较笨拙。Spring为我们提供了一种方便的注册这些BeanPostProcessor的方式,这就是,以下是spring的配置。

Xml代码

<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"       
    xsi:schemaLocation="http://www.springframework.org/schema/beans        
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd        
    http://www.springframework.org/schema/context        
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">        
    <context:annotation-config />        
<beans>  

将隐式地向Spring容器注册了

AutowiredAnnotationBeanPostProcessor 、

CommonAnnotationBeanPostProcessor 、

PersistenceAnnotationBeanPostProcessor

RequiredAnnotationBeanPostProcessor

这4个BeanPostProcessor。

2.使用让Bean定义注解工作起来

Xml代码

<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"       
    xsi:schemaLocation="http://www.springframework.org/schema/beans        
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd        
    http://www.springframework.org/schema/context        
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">        
    <context:component-scan base-package="com.kedacom.ksoa" />        
<beans>   

这里,所有通过元素定义Bean的配置内容已经被移除,仅需要添加一行配置就解决所有问题了——Spring XML配置文件得到了极致的简化(当然配置元数据还是需要的,只不过以注释形式存在罢了)。的base-package属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理。

还允许定义过滤器将基包下的某些类纳入或排除。Spring支持以下4种类型的过滤方式:

过滤器类型 | 表达式范例 | 说明

注解 | org.example.SomeAnnotation | 将所有使用SomeAnnotation注解的类过滤出来

类名指定 | org.example.SomeClass | 过滤指定的类

正则表达式 | com\.kedacom\.spring\.annotation\.web\..* | 通过正则表达式过滤一些类

AspectJ表达式 | org.example..*Service+ | 通过AspectJ表达式过滤一些类

以正则表达式为例,我列举一个应用实例:

Xml代码

<context:component-scan base-package="com.casheen.spring.annotation">        
    <context:exclude-filter type="regex" expression="com\.casheen\.spring\.annotation\.web\..*" />        
<context:component-scan>   

值得注意的是配置项不但启用了对类包进行扫描以实施注释驱动Bean定义的功能,同时还启用了注释驱动自动注入的功能(即还隐式地在内部注册了AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor),因此当使用后,就可以将移除了。

3. 
是不支持spring的@Transcation和EJB的Spring's @Transactional or EJB3's @TransactionAttribute annotation。用此配置可以达到目的。

3、context:annotation-config和context:component-scan区别

请看这篇博文:spring配置注解context:annotation-config和context:component-scan区别

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值