Spring 常用注解

Spring 常用注解

组件注解

  1. @Component
    组件,没有明确的角色即标注普通类。指定某个类是容器的bean,@component(value=“***”)相当于在xml中配置的
    <bean id="**"/>,其中value可以不写。

  2. @Controller
    用于标注一个类是控制器

  3. @Service
    用于标注业务逻辑类(service层),一般是接口的实现类

  4. @Repository
    在数据访问层使用(dao层)
    注意:这几个注解是用于修饰类,当不写value是,value的默认值是类名首字母小写。

注入bean的注解

  1. @Bean
    @Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component这类注解的类里。添加的bean的id为方法名
    a、name:bean id 。name可以省略,省略时name值为方法名。

    下面是@Configuration里的一个例子

    @Configuration
    public class AppConfig 
    {
        @Bean
        public TransferService transferService() 
        {
            return new TransferServiceImpl();
        }
    }
    

    这个配置就等同于之前在xml里的配置

      <beans>
    	    <bean id="transferService" class="com.acme.TransferServiceImpl"/>
     </beans>
    

    b、 autowire: 是否自动注入,默认Autowire.NO

    @bean 也可以依赖其他任意数量的bean,如果TransferService 依赖 AccountRepository,我们可以通过方法参数实现这个依赖

     @Configuration
     public class AppConfig
      {
        	@Bean
       		public TransferService transferService(AccountRepository accountRepository) 
       		{
            	 return new TransferServiceImpl(accountRepository);
            }
     }
    

    c、initMethod:bean的初始化方法。在依赖注入之后执行<bean id="" init-method="">
    destroyMethod: spring容器关闭时bean调用的方法 <bean id="" destroty-method="">

         public class Foo
          {
          		  public void init() {}
           }
        
        public class Bar
         {
           		 public void cleanup()  { }
      	  }
        
        @Configuration
        public class AppConfig 
        {
        
           	 @Bean(initMethod = "init")
          	  public Foo foo()
          	   {
               		 return new Foo();
         	   }
        
            @Bean(destroyMethod = "cleanup")
            public Bar bar()
             {
                return new Bar();
            }
        
        }
    
  2. @Scope
    a、对象在spring容器(IOC容器)中的生命周期
    b、目前,scope的取值有5种取值:

取值解释
singleton单例模式
prototypespring容器在进行输出prototype的bean对象时,会每次都重新生成一个新的对象给请求方,但是只要准备完毕,并且对象实例返回给请求方之后,容器就不在拥有当前对象的引用,请求方需要自己负责当前对象后继生命周期的管理工作,包括该对象的销毁
request<bean id ="requestPrecessor" class="...RequestPrecessor" scope="request" />Spring容器,即XmlWebApplicationContext 会为每个HTTP请求创建一个全新的RequestPrecessor对象,当请求结束后,该对象的生命周期即告结束,如同java web中request的生命周期。当同时有10个HTTP请求进来的时候,容器会分别针对这10个请求创建10个全新的RequestPrecessor实例,且他们相互之间互不干扰
session<bean id ="userPreferences" class="...UserPreferences" scope="session" />Spring容器会为每个独立的session创建属于自己的全新的UserPreferences实例,比request scope的bean会存活更长的时间,其他的方面没区别,如果java web中session的生命周期
globalsession<bean id ="userPreferences" class="...UserPreferences" scope="globalsession" />global session只有应用在基于porlet的web应用程序中才有意义,它映射到porlet的global范围的session,如果普通的servlet的web 应用中使用了这个scope,容器会把它作为普通的session的scope对待。

在这里插入图片描述
3. @DependsOn
用于注解@Component这类注解类,用于强制初始化其他bean

@DepondsOn("other")
@Controller
@Scope("prototype")
public class UserAction
{
}

上面代码指初始化UserAction之前要先初始化other对应的类
4. @Lazy
指定bean是否延时初始化,相当于<bean id="xx" lazy-init=""> ,默认false。@Lazy可以和@Component这一类注解联合使用修饰类,也可以和@Bean一起使用修饰方法

@Component
@Lazy(true)
public class UserAction
{
}

注:此处初始化不是指不执行init-method,而是不创建bean实例和依赖注入。只有当该bean(被@Lazy修饰的类或方法)被其他bean引用(可以是自动注入的方式)或者执行getBean方法获取,才会真正的创建该bean实例,其实这也是BeanFactory的执行方式

自动装配

  1. @Resource
    @Resource默认按byName自动注入
    @Resource依赖注入时查找bean的规则:
    a、既不指定name属性,也不指定type属性,则自动按byName方式进行查找。如果没有找到符合的bean,则回退为一个原始类型进行查找,如果找到就注入。
    在这里插入图片描述
    报错 No qualifying bean of type [java.lang.String] is defined: expected single matching bean but found 2: bucketName,styleName这是因为spring会去找bean元素中的name属性和变量名一致的bean,但因为没有指定name属性,所以找不到然后就按照原始类型String去查找,找到了两个,所以报错。
    b、 只是指定了@Resource注解的name,则按name后的名字去bean元素里查找有与之相等的name属性的bean。
    在这里插入图片描述
    c、只指定@Resource注解的type属性,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
    d、 既指定了@Resource的name属性又指定了type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
  2. @Autowired
    a、首先要知道另一个东西,default-autowire,它是在xml文件中进行配置的,可以设置为byName、byType、constructor和autodetect;比如byName,不用显式的在bean中写出依赖的对象,它会自动的匹配其它bean中id名与本bean的set**相同的,并自动装载。
    b、@Autowired是用在JavaBean中的注解,通过byType形式,用来给指定的字段或方法注入所需的外部资源
    c、autowire四种模式的区别:
模式说明
byName根据属性名自动装配。此项将检查容器并根据名字查找与属性完全一致的bean,并将其与属性自动装配。例如,在bean定义中将autowire设置为byName,而该bean包含master属性(同时提供setMaster()方法),Spring就会查找名为master的bean定义,并用它来装配给master属性
byType如果容器中存在一个与指定属性类型相同的bean,那么将与该属性自动装配。如果存在多个该类型的bean,那么将会跑出异常,并指出不能使用byType方式进行自动装配。若没有找到相匹配的 bean,则什么事都不会发生,属性也不会被设置。可通过dependency-check=“objects”让Spring抛出异常
constructor与byType的方式类似,不同之处在于它应用于构造器参数。如果在容器中没有找到与构造器参数类型一致的bean,将会跑出异常
autodetect通过bean类的自省机制(introspection)来决定是使用constructor还是byType方式进行自动装配。如果发现默认的构造器,将使用byType方式

c、bean实例化和@autowired装配过程:
1) 一切都是从bean工厂的getBean方法开始的,一旦该方法调用总会返回一个bean实例,无论当前是否存在,不存在就实例化一个并装配,否则就直接返回
2) 实例化和装配过程中会多次递归吊笼getBean方法来解决类之间的依赖
3) Spring几乎考虑了所有可能性,所以方法特别复杂但是完整有条理
4) @Autowired最终是根据类型来查找和装配元素的,但是我们设置了<beans default-autowire="byName"/>之后会影响最终的类型匹配查找。因为在前面有根绝BeanDefinition的autowire类型设置PropertyValue值的一步,其中会有新的实例创建和注册。就是autowireByName方法
d、Setter 方法中的 @Autowired
在javaBean中的setter方法中使用@Atuowired注解,他会在方法中执行byType自动装配
在这里插入图片描述
e、属性中的 @Autowired
在这里插入图片描述
f、构造函数中的 @Autowired
在这里插入图片描述
g、@Autowired 的(required=false)选项
默认情况下,@Autowired注解意味着依赖是必须的,他类似 @Required注解,然而可以关闭默认行为

  1. @Qualifier
    Qualifier的意思是合格者,通过这个标示,表明了哪个实现类才是我们所需要的,添加@Qualifier注解,需要注意的是 @Qualifier的参数名称为我们之前定义@Service注解的名称之一。
    在这里插入图片描述

AOP 相关注解

  1. @Aspect
    修饰类,表示该类为切面类,把当前类标识为一个切面供容器读取。
  2. @Before(“pointcut_expresisson”)
    修饰方法,标识一个前置增强方法。有一个value属性用于指定切入点表达式。用于对膜表方法(切入点表达式指定的方法)执行前做增强处理。用于权限检查,登录检查
  3. @AfterReturning
    修饰方法,标识一个后置增强方法,方法正常退出时执行
    常用属性:pointcut/value:定义切入点;returning:指定一个参数名,用于接受目标方法正常结束返回的值,在增强方法中定义同名的参数
  4. @AfterThrowing
    修饰方法,异常抛出增强。当目标程序方法抛出异常或者异常无法捕获是,做增强处理
    常用属性:pointcut/value:指定切入点表达式;throwing:指定一个形参,在增强方法中定义同名的形参,用于访问目标方法抛出的异常
  5. @After
    修饰方法,无论方法是否正常结束都会调用该增强处理(@After = @AfterReturning+@AfterThrowing),一般用于资源释放。
    有一个value属性,用于指定切入点表达式。
  6. @Around
    修饰方法,环绕增强,该处理可以使目标方法执行之前和执行之后植入增强处理, @Arround = @Before + @AfterReturning
    有一个value属性,指定切入点表达式。
    @Around通常需要在线程安全下使用,如果@Befor和@AfterReturning可以处理就没必要使用
    当定义一个@Around处理时,增强方法第一形参需要是ProceedingJoinPoint类型,ProceedingJoinPoint有一个Object proceed()方法,用于执行目标方法,返回对象当然也可以为目标方法传递数组参数。
  7. @Pointcut
    修饰方法,定义一个切入点,用于被其他增强调用。
    execution切点函数:
    execution(方法修饰符(可选) 返回类型 方法名 参数 异常模式(可选))
    参数部分允许使用通配符:
    匹配任意字符,但只能匹配一个元素
    匹配任意字符,可以匹配任意多个元素,表示类时,必须和*联合使用
    必须跟在类名后面,如Horseman+,表示类本身和继承或扩展指定类的所有类
  8. @Order
    当不同的切面中的两个增强处理需要在同一个连接点被织入时,spring aop可以指定不同切面类的增强处理优先级。
    有一个value属性,指定一个int值,属性值越小优先级越高。

@Aspect
public class UserAdvice{

@Pointcut("execution(* com.User*.*(..))")
public void userAdvice(){}

@Before(value="userAdvice()")
public void authority(){
	System.out.println("权限检查。。。");
}

@AfterReturning(pointcut="userAdvice")
public void log(){
	System.out.println("写入日志。。。");
}

@After("userAdvice()")
public void release(){
	System.out.println("资源释放。。。");
}

@Around("userAdvice()")
public void arround(ProceedingJoinPoint joinPoint){
	System.out.println("开启事务。。。");
	joinPoint.proceed(jointPoint.getArgs());
	System.out.println("关闭事务。。。");
}
}

配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"  
        xmlns:context="http://www.springframework.org/schema/context"  
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:aop="http://www.springframework.org/schema/aop"   
        xsi:schemaLocation="  
            http://www.springframework.org/schema/beans       
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
            http://www.springframework.org/schema/context   
            http://www.springframework.org/schema/context/spring-context-3.0.xsd  
            http://www.springframework.org/schema/aop  
            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">  
      
        <context:component-scan base-package="com" />  <!--自动扫描-->
    	<aop:aspectj-autoproxy></aop:aspectj-autoproxy><!--开启@AspectJ支持-->
    </beans> 

测试类

public class TestAnnotation{
    @Test 
    public void test1(){
        ClassPathXmlApplicationContext application=new ClassPathXmlApplicationContext("applicationContext.xml");
        //配置文件里只有一行就是开启自动扫描” <context:component-scan base-package="com" /> “
       IUserDao userDao = application.getBean("userDao",UserDao.class);
       userDao.listUsers();
    }
} 

输出结果

constructor...................
post_constructor.................
after_properties_set..............
开启事务。。。
权限检查。。。
System.out.println("查询所有用户");
关闭事务。。。
资源释放。。。
写入日志。。。
pre_destroty.................
destry.............
pre_destroty.................
destry.............

Java配置类相关注解

  1. @Configuration
    从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含一个或多个被@Bean注解的方法,这些方法结汇被AnnotationConfigapplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
    注意:不能修饰final类型、匿名类,被嵌套的configuration必须是静态类
    一、用@Configuration加载soring
    a、@Configuration配置spring并启动spring容器
    @Configuration标注在类上,相当于把该类作为spring的xml配置文件中的,作用为:配置spring容器(应用上下文)

在这里插入图片描述在这里插入图片描述在这里插入图片描述
b、@Configuration启动容器+@Bean注册Bean,@Bean下管理bean的生命周期
@Bean标注在方法上(返回某个实例的方法),等价于spring的xml配置文件中的,作用为:注册bean对象
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
@Bean下管理bean的生命周期
可以使用基于 Java 的配置来管理 bean 的生命周期。@Bean 支持两种属性,即 initMethod 和destroyMethod,这些属性可用于定义生命周期方法。在实例化 bean 或即将销毁它时,容器便可调用生命周期方法。生命周期方法也称为回调方法,因为它将由容器调用。使用 @Bean 注释注册的 bean 也支持 JSR-250 规定的标准 @PostConstruct 和 @PreDestroy 注释。如果您正在使用 XML 方法来定义 bean,那么就应该使用 bean 元素来定义生命周期回调方法。以下代码显示了在 XML 配置中通常使用 bean 元素定义回调的方法。
在这里插入图片描述
c、@Configuration启动容器+@Component注册Bean
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
d、使用 AnnotationConfigApplicationContext 注册 AppContext 类的两种方法
在这里插入图片描述
f、配置Web应用程序(web.xml中配置AnnotationConfigApplicationContext)
过去,您通常要利用 XmlWebApplicationContext 上下文来配置 Spring Web 应用程序,即在 Web 部署描述符文件 web.xml 中指定外部 XML 上下文文件的路径。XMLWebApplicationContext 是 Web 应用程序使用的默认上下文类。以下代码描述了 web.xml 中指向将由 ContextLoaderListener 监听器类载入的外部 XML 上下文文件的元素。
在这里插入图片描述
现在,您要将 web.xml 中的上述代码更改为使用 AnnotationConfigApplicationContext 类。切记,XmlWebApplicationContext 是 Spring 为 Web 应用程序使用的默认上下文实现,因此您永远不必在您的web.xml 文件中显式指定这个上下文类。现在,您将使用基于 Java 的配置,因此在配置 Web 应用程序时,需要在web.xml 文件中指定 AnnotationConfigApplicationContext 类。上述代码将修改如下:
在这里插入图片描述
以上修改后的 web.xml 现在定义了 AnnotationConfigWebApplicationContext 上下文类,并将其作为上下文参数和 servlet 元素的一部分。上下文配置位置现在指向 AppContext 配置类。这非常简单。下一节将演示 bean 的生命周期回调和范围的实现。
g、@Configuation总结
@Configuation等价于<beans></beans>
@Bean等价于<bean></bean>
@ComponentScan等价于<context:component-scan base-package="com.dxz.demo"/>
二、组合多个配置类
a 、在@configuration中引入spring的xml配置文件
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
b、在@configuration中引入其它注解配置在这里插入图片描述
在这里插入图片描述
f、@configuration嵌套(嵌套的Configuration必须是静态类)
通过配置类嵌套的配置类,达到组合多个配置类的目的。但注意内部类必须是静态类。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
2. @Import
修饰Java类,用于向当前配置类导入其他java配置类

  1. @ImportResource
    修饰Java类,用于向当前注解类导入xml配置文件
    上面两个都是用于配置的导入相当于元素

  2. @Value
    修饰成员变量或者 方法构造器的参数,常用于注入属性文件中的值。

注意:@Value不能对 static 属性注入。
5. @ConfigurationProperties
用于从属性文件中注入值。

@Component
@ConfigurationProperties(prefix="mybatis.configuration")
public class MybatisProperties {

private String configLocation ; //配置文件的路径
private String mapperLocations; //配置Mapper映射文件的路径
private String typeAliasPackage; //别名的实体路径
public String getConfigLocation() {
    return configLocation;
}

public void setConfigLocation(String configLocation) {
    this.configLocation = configLocation;
}

public String getMapperLocations() {
    return mapperLocations;
}

public void setMapperLocations(String mapperLocations) {
    this.mapperLocations = mapperLocations;
}

public String getTypeAliasPackage() {
    return typeAliasPackage;
}

public void setTypeAliasPackage(String typeAliasPackage) {
    this.typeAliasPackage = typeAliasPackage;
}
}

mybatis.configuration.mapperLocations=classpath:mybatis/mapper/*.xml
mybatis.configuration.typeAliasPackage=com.example.domain
mybatis.configuration.configLocation=classpath:mybatis/mybatis-config.xml
  1. @PropertySource(value=“classpath:jdbc.properties”)
    用于加载配置文件
    包含属性:ingnoreResourceNotFound:当资源文件找不到的时是否会忽略配置,一般用于可选项
    encoding:资源文件使用什么编码格式

    @Configuration
    @PropertySource(value="classpath:jdbc.properties")
    public class DatasourceConfig {
    	private Logger logger = LoggerFactory.getLogger(DatasourceConfig.class);
    
    @Value("${spring.datasource.url}")
    private String dbUrl;
    
    @Value("${spring.datasource.type}")
    private String dbType;
    
    @Value("${spring.datasource.username}")
    private String username;
    
    @Value("${spring.datasource.password}")
    private String password;
    
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    
    @Value("${spring.datasource.initialSize}")
    private int initialSize;
    
    @Value("${spring.datasource.maxActive}")
    private int maxActive;
    
    @Value("${spring.datasource.maxWait}")
    private int maxWait;
    
    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;
    
    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;
    
    @Value("${spring.datasource.validationQuery}")
    private String validationQuery;
    
    @Value("${spring.datasource.testWhileIdle}")
    private boolean testWhileIdle;
    
    @Value("${spring.datasource.testOnBorrow}")
    private boolean testOnBorrow;
    
    @Value("${spring.datasource.testOnReturn}")
    private boolean testOnReturn;
    
    @Value("${spring.datasource.poolPreparedStatements}")
    private boolean poolPreparedStatements;
    
    @Value("${spring.datasource.filters}")
    private String filters;
    
    @Value("${spring.datasource.druidLoginName}")  
    private String druidLoginName;  
      
    @Value("${spring.datasource.druidPassword}")  
    private String druidPassword; 
    
    @Bean(name="dataSource",destroyMethod = "close", initMethod="init")
    @Primary 
    public DataSource dataSource(){  
        DruidDataSource datasource = new DruidDataSource();  
        try {  
            datasource.setUrl(this.dbUrl);  
            datasource.setDbType(dbType);
            datasource.setUsername(username);  
            datasource.setPassword(password);  
            datasource.setDriverClassName(driverClassName);  
            datasource.setInitialSize(initialSize);  
            datasource.setMinIdle(minIdle);  
            datasource.setMaxActive(maxActive);  
            datasource.setMaxWait(maxWait);  
            datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);  
            datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);  
            datasource.setValidationQuery(validationQuery);  
            datasource.setTestWhileIdle(testWhileIdle);  
            datasource.setTestOnBorrow(testOnBorrow);  
            datasource.setTestOnReturn(testOnReturn);  
            datasource.setPoolPreparedStatements(poolPreparedStatements);  
            datasource.setFilters(filters);  
        } catch (SQLException e) {  
            logger.error("druid configuration initialization filter", e);  
        }  
        return datasource;  
    } 
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值