Spring系列之Spring常用注解总结

 

传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop、事物,这么做有两个缺点:
1、如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大;如果按需求分开.xml文件,那么.xml文件又会非常多。总之这将导致配置文件的可读性与可维护性变得很低。
2、在开发中在.java文件和.xml文件之间不断切换,是一件麻烦的事,同时这种思维上的不连贯也会降低开发的效率。
为了解决这两个问题,Spring引入了注解,通过"@XXX"的方式,让注解与Java Bean紧密结合,既大大减少了配置文件的体积,又增加了Java Bean的可读性与内聚性。

不使用注解:

先看一个不使用注解的Spring示例,在这个示例的基础上,改成注解版本的,这样也能看出使用与不使用注解之间的区别,先定义一个老虎:

  1. package com.spring.model;
  2.  
  3. public class Tiger {
  4.  
  5. private String tigerName="TigerKing";
  6.  
  7. public String toString(){
  8. return "TigerName:"+tigerName;
  9. }
  10. }

再定义一个猴子:

  1. package com.spring.model;
  2.  
  3. public class Monkey {
  4.  
  5. private String monkeyName = "MonkeyKing";
  6.  
  7. public String toString(){
  8. return "MonkeyName:" + monkeyName;
  9. }
  10.  
  11. }

定义一个动物园:

  1. package com.spring.model;
  2.  
  3. public class Zoo {
  4. private Tiger tiger;
  5. private Monkey monkey;
  6.  
  7. public Tiger getTiger() {
  8. return tiger;
  9. }
  10. public void setTiger(Tiger tiger) {
  11. this.tiger = tiger;
  12. }
  13. public Monkey getMonkey() {
  14. return monkey;
  15. }
  16. public void setMonkey(Monkey monkey) {
  17. this.monkey = monkey;
  18. }
  19.  
  20. public String toString(){
  21. return tiger + "\n" + monkey;
  22. }
  23.  
  24. }

spring的配置文件这么写:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:p="http://www.springframework.org/schema/p"
  6. xmlns:context="http://www.springframework.org/schema/context"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  11. ">
  12.  
  13. <bean id="zoo" class="com.spring.model.Zoo" >
  14. <property name="tiger" ref="tiger" />
  15. <property name="monkey" ref="monkey" />
  16. </bean>
  17.  
  18. <bean id="tiger" class="com.spring.model.Tiger" />
  19. <bean id="monkey" class="com.spring.model.Monkey" />
  20.  
  21. </beans>

测试方法:

  1. public class TestAnnotation {
  2. /**
  3. * 不使用注解
  4. */
  5. @Test
  6. public void test(){
  7. //读取配置文件
  8. ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext2.xml");
  9. Zoo zoo=(Zoo) ctx.getBean("zoo");
  10. System.out.println(zoo.toString());
  11. }
  12. }

都很熟悉,权当复习一遍了。

1、@Autowired

@Autowired顾名思义,就是自动装配,其作用是为了消除代码Java代码里面的getter/setter与bean属性中的property。当然,getter看个人需求,如果私有属性需要对外提供的话,应当予以保留。

@Autowired默认按类型匹配的方式,在容器查找匹配的Bean,当有且仅有一个匹配的Bean时,Spring将其注入@Autowired标注的变量中。

因此,引入@Autowired注解,先看一下spring配置文件怎么写:

  1. 1 <?xml version="1.0" encoding="UTF-8"?>
  2. 2 <beans
  3. 3 xmlns="http://www.springframework.org/schema/beans"
  4. 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. 5 xmlns:p="http://www.springframework.org/schema/p"
  6. 6 xmlns:context="http://www.springframework.org/schema/context"
  7. 7 xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. 8 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  9. 9 http://www.springframework.org/schema/context
  10. 10 http://www.springframework.org/schema/context/spring-context-3.0.xsd
  11. 11 ">
  12. 12
  13. 13 <context:component-scan base-package="com.spring" />
  14. 14
  15. 15 <bean id="zoo" class="com.spring.model.Zoo" />
  16. 16 <bean id="tiger" class="com.spring.model.Tiger" />
  17. 17 <bean id="monkey" class="com.spring.model.Monkey" />
  18. 18
  19. 19 </beans>

注意第13行,使用必须告诉spring一下我要使用注解了,告诉的方式有很多,<context:component-scan base-package="xxx" />是一种最简单的,spring会自动扫描xxx路径下的注解。

看到第15行,原来zoo里面应当注入两个属性tiger、monkey,现在不需要注入了。再看下,Zoo.java也很方便,把getter/setter都可以去掉:

  1. package com.spring.model;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4.  
  5. public class Zoo {
  6.  
  7. @Autowired
  8. private Tiger tiger;
  9.  
  10. @Autowired
  11. private Monkey monkey;
  12.  
  13. public String toString(){
  14. return tiger + "\n" + monkey;
  15. }
  16.  
  17. }

这里@Autowired注解的意思就是,当Spring发现@Autowired注解时,将自动在代码上下文中找到和其匹配(默认是类型匹配)的Bean,并自动注入到相应的地方去。

有一个细节性的问题是,假如bean里面有两个property,Zoo.java里面又去掉了属性的getter/setter并使用@Autowired注解标注这两个属性那会怎么样?答案是Spring会按照xml优先的原则去Zoo.java中寻找这两个属性的getter/setter,导致的结果就是初始化bean报错。

OK,假设此时我把.xml文件的16行、17行两行给去掉,再运行,会抛出异常:

  1. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'zoo': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.spring.model.Tiger com.spring.model.Zoo.tiger; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.spring.model.Tiger] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
  2. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
  3. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
  4. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
  5. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
  6. at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
  7. at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
  8. at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
  9. at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
  10. at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
  11. at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
  12. at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
  13. at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
  14. at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
  15. at com.spring.test.TestAnnotation.test(TestAnnotation.java:16)
  16. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  17. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
  18. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
  19. at java.lang.reflect.Method.invoke(Method.java:597)
  20. at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
  21. at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
  22. at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
  23. at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
  24. at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
  25. at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
  26. at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
  27. at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
  28. at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
  29. at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
  30. at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
  31. at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
  32. at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
  33. at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
  34. at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
  35. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
  36. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
  37. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
  38. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
  39. Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.spring.model.Tiger com.spring.model.Zoo.tiger; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.spring.model.Tiger] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
  40. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502)
  41. at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
  42. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
  43. ... 36 more
  44. Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.spring.model.Tiger] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
  45. at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:920)
  46. at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:789)
  47. at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
  48. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
  49. ... 38 more

因为,@Autowired注解要去寻找的是一个Bean,Tiger和Monkey的Bean定义都给去掉了,自然就不是一个Bean了,Spring容器找不到也很好理解。那么,如果属性找不到我不想让Spring容器抛出异常,而就是显示null,可以吗?可以的,其实异常信息里面也给出了提示了,就是将@Autowired注解的required属性设置为false即可:

  1. package com.spring.model;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4.  
  5. public class Zoo {
  6.  
  7. @Autowired(required=false)
  8. private Tiger tiger;
  9.  
  10. @Autowired(required=false)
  11. private Monkey monkey;
  12.  
  13. public String toString(){
  14. return tiger + "\n" + monkey;
  15. }
  16.  
  17. }

此时,找不到tiger、monkey两个属性,Spring容器不再抛出异常而是认为这两个属性为null。

2、Qualifier(指定注入Bean的名称)

如果容器中有一个以上匹配的Bean,则可以通过@Qualifier注解限定Bean的名称,看下面的例子:

定义一个Car接口:

  1. package com.spring.service;
  2.  
  3. public interface ICar {
  4.  
  5. public String getCarName();
  6. }

两个实现类BMWCar和BenzCar:

  1. package com.spring.service.impl;
  2.  
  3. import com.spring.service.ICar;
  4.  
  5. public class BMWCar implements ICar{
  6.  
  7. public String getCarName(){
  8. return "BMW car";
  9. }
  10. }
  1. package com.spring.service.impl;
  2.  
  3. import com.spring.service.ICar;
  4.  
  5. public class BenzCar implements ICar{
  6.  
  7. public String getCarName(){
  8. return "Benz car";
  9. }
  10. }

再写一个CarFactory,引用car(这里先不用@Qualifier注解):

  1. package com.spring.model;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4.  
  5. import com.spring.service.ICar;
  6.  
  7. public class CarFactory {
  8.  
  9. @Autowired
  10. private ICar car;
  11.  
  12. public String toString(){
  13. return car.getCarName();
  14. }
  15.  
  16. }

配置文件:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:p="http://www.springframework.org/schema/p"
  6. xmlns:context="http://www.springframework.org/schema/context"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  11. ">
  12.  
  13. <context:component-scan base-package="com.spring" />
  14.  
  15. <!-- Autowired注解配合Qualifier注解 -->
  16. <bean id="carFactory" class="com.spring.model.CarFactory" />
  17. <bean id="bmwCar" class="com.spring.service.impl.BMWCar" />
  18. <bean id="benz" class="com.spring.service.impl.BenzCar" />
  19.  
  20. </beans>

测试方法:

  1. /**
  2. * Autowired注解配合Qualifier注解
  3. */
  4. @Test
  5. public void test1(){
  6. //读取配置文件
  7. ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext2.xml");
  8. CarFactory carFactory=(CarFactory) ctx.getBean("carFactory");
  9. System.out.println(carFactory.toString());
  10. }

运行一下,不用说,一定是报错的,Car接口有两个实现类,Spring并不知道应当引用哪个实现类。

  1. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carFactory': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:
    Could not autowire field: private com.spring.service.ICar com.spring.model.CarFactory.car; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
    No unique bean of type [com.spring.service.ICar] is defined: expected single matching bean but found 2: [bmwCar, benz]
  2. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
  3. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
  4. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
  5. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
  6. at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
  7. at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
  8. at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
  9. at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
  10. at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
  11. at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
  12. at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
  13. at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
  14. at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
  15. at com.spring.test.TestAnnotation.test1(TestAnnotation.java:25)
  16. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  17. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
  18. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
  19. at java.lang.reflect.Method.invoke(Method.java:597)
  20. at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
  21. at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
  22. at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
  23. at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
  24. at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
  25. at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
  26. at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
  27. at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
  28. at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
  29. at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
  30. at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
  31. at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
  32. at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
  33. at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
  34. at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
  35. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
  36. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
  37. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
  38. at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
  39. Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.spring.service.ICar com.spring.model.CarFactory.car; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.spring.service.ICar] is defined: expected single matching bean but found 2: [bmwCar, benz]
  40. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502)
  41. at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
  42. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
  43. ... 36 more
  44. Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.spring.service.ICar] is defined: expected single matching bean but found 2: [bmwCar, benz]
  45. at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:796)
  46. at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:703)
  47. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:474)
  48. ... 38 more

出现这种情况通常有两种解决办法:
(1)、在配置文件中删除其中一个实现类,Spring会自动去base-package下寻找Car接口的实现类,发现Car接口只有一个实现类,便会直接引用这个实现类。
(2)、实现类就是有多个该怎么办?此时可以使用@Qualifier注解来指定Bean的名称:

  1. package com.spring.model;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Qualifier;
  5.  
  6. import com.spring.service.ICar;
  7.  
  8. public class CarFactory {
  9.  
  10. @Autowired
  11. @Qualifier("bmwCar")
  12. private ICar car;
  13.  
  14. public String toString(){
  15. return car.getCarName();
  16. }
  17.  
  18. }

此处会注入名为"bmwCar"的Bean。

3、Resource

@Resource注解与@Autowired注解作用非常相似,这个就简单说了,看例子:

  1. package com.spring.model;
  2.  
  3. import javax.annotation.Resource;
  4.  
  5. public class Zoo1 {
  6.  
  7. @Resource(name="tiger")
  8. private Tiger tiger;
  9.  
  10. @Resource(type=Monkey.class)
  11. private Monkey monkey;
  12.  
  13. public String toString(){
  14. return tiger + "\n" + monkey;
  15. }
  16. }

这是详细一些的用法,说一下@Resource的装配顺序:
(1)、@Resource后面没有任何内容,默认通过name属性去匹配bean,找不到再按type去匹配
(2)、指定了name或者type则根据指定的类型去匹配bean
(3)、指定了name和type则根据指定的name和type去匹配bean,任何一个不匹配都将报错

然后,区分一下@Autowired和@Resource两个注解的区别:
(1)、@Autowired默认按照byType方式进行bean匹配,@Resource默认按照byName方式进行bean匹配
(2)、@Autowired是Spring的注解,@Resource是J2EE的注解,这个看一下导入注解的时候这两个注解的包名就一清二楚了
Spring属于第三方的,J2EE是Java自己的东西,因此,建议使用@Resource注解,以减少代码和Spring之间的耦合。

4、Service

上面这个例子,还可以继续简化,因为spring的配置文件里面还有15行~17行三个bean,下一步的简化是把这三个bean也给去掉,使得spring配置文件里面只有一个自动扫描的标签,增强Java代码的内聚性并进一步减少配置文件。

要继续简化,可以使用@Service。先看一下配置文件,当然是全部删除了:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:p="http://www.springframework.org/schema/p"
  6. xmlns:context="http://www.springframework.org/schema/context"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context-3.0.xsd
  11. ">
  12.  
  13. <context:component-scan base-package="com.spring" />
  14.  
  15. </beans>

是不是感觉很爽?起码我觉得是的。OK,下面以Zoo.java为例,其余的Monkey.java和Tiger.java都一样:

  1. package com.spring.model;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Service;
  5.  
  6. @Service
  7. public class Zoo {
  8.  
  9. @Autowired
  10. private Tiger tiger;
  11.  
  12. @Autowired
  13. private Monkey monkey;
  14.  
  15. public String toString(){
  16. return tiger + "\n" + monkey;
  17. }
  18.  
  19. }

这样,Zoo.java在Spring容器中存在的形式就是"zoo",即可以通过ApplicationContext的getBean("zoo")方法来得到Zoo.java。@Service注解,其实做了两件事情:
(1)、声明Zoo.java是一个bean,这点很重要,因为Zoo.java是一个bean,其他的类才可以使用@Autowired将Zoo作为一个成员变量自动注入。
(2)、Zoo.java在bean中的id是"zoo",即类名且首字母小写。

如果,我不想用这种形式怎么办,就想让Zoo.java在Spring容器中的名字叫做"Zoo",可以的:

  1. package com.spring.model;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.context.annotation.Scope;
  5. import org.springframework.stereotype.Service;
  6.  
  7. @Service("Zoo")
  8. @Scope("prototype")
  9. public class Zoo {
  10.  
  11. @Autowired
  12. private Tiger tiger;
  13.  
  14. @Autowired
  15. private Monkey monkey;
  16.  
  17. public String toString(){
  18. return tiger + "\n" + monkey;
  19. }
  20.  
  21. }

这样,就可以通过ApplicationContext的getBean("Zoo")方法来得到Zoo.java了。

这里我还多加了一个@Scope注解,应该很好理解。因为Spring默认产生的bean是单例的,假如我不想使用单例怎么办,xml文件里面可以在bean里面配置scope属性。注解也是一样,配置@Scope即可,默认是"singleton"即单例,"prototype"表示原型即每次都会new一个新的出来。

————————————————————————————————————————————————————————————————————

使用注解来构造IoC容器
用注解来向Spring容器注册Bean。需要在applicationContext.xml中注册<context:component-scan base-package=”pagkage1[,pagkage2,…,pagkageN]”/>。

如:在base-package指明一个包

  1. <context:component-scan base-package="cn.gacl.java"/>

表明cn.gacl.java包及其子包中,如果某个类的头上带有特定的注解【@Component/@Repository/@Service/@Controller】,就会将这个对象作为Bean注册进Spring容器。也可以在<context:component-scan base-package=” ”/>中指定多个包,如:

  1. <context:component-scan base-package="cn.gacl.dao.impl,cn.gacl.service.impl,cn.gacl.action"/>

多个包逗号隔开。

1、@Component
@Component是所有受Spring 管理组件的通用形式,@Component注解可以放在类的头上,@Component不推荐使用。

2、@Controller
@Controller对应表现层的Bean,也就是Action,例如:

  1. @Controller
  2. @Scope("prototype")
  3. public class UserAction extends BaseAction<User>{
  4. ……
  5. }

使用@Controller注解标识UserAction之后,就表示要把UserAction交给Spring容器管理,Spring容器中会存在一个名字为"userAction"action,这个名字是根据UserAction类名来取的。注意:如果@Controller不指定其value【@Controller】,则默认的bean名字为这个类的类名首字母小写如果指定value【@Controller(value="UserAction")】或者【@Controller("UserAction")】,则使用value作为bean的名字

这里的UserAction还使用了@Scope注解,@Scope("prototype")表示将Action的范围声明为原型,可以利用容器的scope="prototype"来保证每一个请求有一个单独的Action来处理,避免strutsAction的线程安全问题。spring 默认scope 是单例模式(scope="singleton"),这样只会创建一个Action对象,每次访问都是同一Action对象,数据不安全,struts2 是要求每次次访问都对应不同的Actionscope="prototype" 可以保证当有请求的时候都创建一个Action对象。

3、@Service
@Service对应的是业务层Bean,例如:

  1. @Service("userService")
  2. public class UserServiceImpl implements UserService {
  3. ………
  4. }

@Service("userService")注解是告诉Spring,当Spring要创建UserServiceImpl的的实例时,bean的名字必须叫做"userService",这样当Action需要使用UserServiceImpl的的实例时,就可以由Spring创建好的"userService",然后注入给Action:在Action只需要声明一个名字叫"userService"的变量来接收由Spring注入的"userService"即可,具体代码如下:

  1. // 注入userService
  2. @Resource(name = "userService")
  3. private UserService userService;

注意:在Action声明的"userService"变量的类型必须是"UserServiceImpl"或者是其父类"UserService",否则由于类型不一致而无法注入,由于Action中的声明的"userService"变量使用了@Resource注解去标注,并且指明了其name = "userService",这就等于告诉Spring,说我Action要实例化一个"userService",你Spring快点帮我实例化好,然后给我,当Spring看到userService变量上的@Resource的注解时,根据其指明的name属性可以知道,Action中需要用到一个UserServiceImpl的实例,此时Spring就会把自己创建好的名字叫做"userService"的UserServiceImpl的实例注入给Action中的"userService"变量,帮助Action完成userService的实例化,这样在Action中就不用通过"UserService userService = new UserServiceImpl();"这种最原始的方式去实例化userService了。如果没有Spring,那么当Action需要使用UserServiceImpl时,必须通过"UserService userService = new UserServiceImpl();"主动去创建实例对象,但使用了Spring之后,Action要使用UserServiceImpl时,就不用主动去创建UserServiceImpl的实例了,创建UserServiceImpl实例已经交给Spring来做了,Spring把创建好的UserServiceImpl实例给Action,Action拿到就可以直接用了。Action由原来的主动创建UserServiceImpl实例后就可以马上使用,变成了被动等待由Spring创建好UserServiceImpl实例之后再注入给Action,Action才能够使用。这说明Action对"UserServiceImpl"类的“控制权”已经被“反转”了,原来主动权在自己手上,自己要使用"UserServiceImpl"类的实例,自己主动去new一个出来马上就可以使用了,但现在自己不能主动去new "UserServiceImpl"类的实例,new "UserServiceImpl"类的实例的权力已经被Spring拿走了,只有Spring才能够new "UserServiceImpl"类的实例,而Action只能等Spring创建好"UserServiceImpl"类的实例后,再“恳求”Spring把创建好的"UserServiceImpl"类的实例给他,这样他才能够使用"UserServiceImpl",这就是Spring核心思想“控制反转”,也叫“依赖注入”,“依赖注入”也很好理解,Action需要使用UserServiceImpl干活,那么就是对UserServiceImpl产生了依赖,Spring把Acion需要依赖的UserServiceImpl注入(也就是“给”)给Action,这就是所谓的“依赖注入”。对Action而言,Action依赖什么东西,就请求Spring注入给他,对Spring而言,Action需要什么,Spring就主动注入给他。

4、@ Repository
@Repository对应数据访问层Bean ,例如:

  1. @Repository(value="userDao")
  2. public class UserDaoImpl extends BaseDaoImpl<User> {
  3. ………
  4. }

@Repository(value="userDao")注解是告诉Spring,让Spring创建一个名字叫"userDao"的UserDaoImpl实例。

当Service需要使用Spring创建的名字叫"userDao"的UserDaoImpl实例时,就可以使用@Resource(name = "userDao")注解告诉Spring,Spring把创建好的userDao注入给Service即可。

  1. // 注入userDao,从数据库中根据用户Id取出指定用户时需要用到
  2. @Resource(name = "userDao")
  3. private BaseDao<User> userDao;

—————————————————————————————————————————————————————————————————————

Spring常用注解汇总 
本文汇总了Spring的常用注解,以方便大家查询和使用,具体如下:

使用注解之前要开启自动扫描功能,其中base-package为需要扫描的包(含子包)。

  1. <context:component-scan base-package="cn.test"/>

@Configuration把一个类作为一个IoC容器,它的某个方法头上如果注册了@Bean,就会作为这个Spring容器中的Bean。
@Scope注解 作用域
@Lazy(true) 表示延迟初始化
@Service用于标注业务层组件、 
@Controller用于标注控制层组件(如struts中的action)
@Repository用于标注数据访问组件,即DAO组件。
@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
@Scope用于指定scope作用域的(用在类上)
@PostConstruct用于指定初始化方法(用在方法上)
@PreDestory用于指定销毁方法(用在方法上)
@DependsOn:定义Bean初始化及销毁时的顺序
@Primary:自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常
@Autowired 默认按类型装配,如果我们想使用按名称装配,可以结合@Qualifier注解一起使用。如下:
@Autowired @Qualifier("personDaoBean") 存在多个实例配合使用
@Resource默认按名称装配,当找不到与名称匹配的bean才会按类型装配。
@PostConstruct 初始化注解
@PreDestroy 摧毁注解 默认 单例  启动就加载
@Async异步方法调用

Spring系列之Spring常用注解总结 转载的更多相关文章

  1. spring boot的一些常用注解

    spring boot的一些常用注解: 使用@SpringBootApplication注释: 许多Spring Boot开发人员喜欢他们的应用程序使用自动配置,组件扫描,并能够在其“应用程序类”上定 ...

  2. Solon Web 开发,十四、与Spring、Jsr330的常用注解对比

    Solon Web 开发 一.开始 二.开发知识准备 三.打包与运行 四.请求上下文 五.数据访问.事务与缓存应用 六.过滤器.处理.拦截器 七.视图模板与Mvc注解 八.校验.及定制与扩展 九.跨域 ...

  3. Spring系列(七) Spring MVC 异常处理

    Servlet传统异常处理 Servlet规范规定了当web应用发生异常时必须能够指明, 并确定了该如何处理, 规定了错误信息应该包含的内容和展示页面的方式.(详细可以参考servlet规范文档) 处 ...

  4. Spring系列之Spring常用注解总结

    传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop.事物,这么做有两个缺点:1.如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大:如果按需求分开.xml文件 ...

  5. Spring 系列之Spring常用注解总结

    传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop.实物,这么做有两个缺点: 1.如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大:如果按需求分开.xml文 ...

  6. Spring系列之手写注解与配置文件的解析

    目录 Spring系列之IOC的原理及手动实现 Spring系列之DI的原理及手动实现 Spring系列之AOP的原理及手动实现 引入 在前面我们已经完成了IOC,DI,AOP的实现,基本的功能都已经 ...

  7. spring,spring mvc,mybatis 常用注解

    文章来源:https://www.cnblogs.com/hello-tl/p/9209063.html  0.在spring,soring mvc, mybistis 中的常用注解有一下 <! ...

  8. Spring和SpringMVC的常用注解

    Spring的部分: 使用注解之前要开启自动扫描功能 其中base-package为需要扫描的包(含子包). <context:component-scan base-package=" ...

  9. Spring系列(零) Spring Framework 文档中文翻译

    Spring 框架文档(核心篇1和2) Version 5.1.3.RELEASE 最新的, 更新的笔记, 支持的版本和其他主题,独立的发布版本等, 是在Github Wiki 项目维护的. 总览 历 ...

随机推荐

  1. 解决ubuntu下firefox的flash全屏后不能恢复问题 ZT

    sudo mkdir /etc/adobe echo "OverrideGPUValidation=true" >~/mms.cfg sudo mv ~/mms.cfg /e ...

  2. 常见模块(一) time/datetime

    1 time模块 1)时间三种格式的转化 2)time模块的相关方法 time.time()  打印当前时间的时间戳 单位是秒 距离1970年1月1日到当前的时间差 time.sleep(n)     ...

  3. centos安装多个tomcat

    1.参考前文安装jdk.第一个tomcat 2.安装第二个tomcat后,修改/etc/profile vi /etc/profile #tomcat1 export CATALINA_BASE=/o ...

  4. 深入Session2

    一.分布式环境Session的处理方法 分布式环境下要保持会话跟踪最简单的方式是只依靠客户端Cookie保存,不过大多数情况下还需要用到Session,一般的处理方式如下: 1.Session复制 每 ...

  5. WPF项目中解决ConfigurationManager不能用(转)

    https://blog.csdn.net/MOESECSDN/article/details/78107888 在WPF项目中遇到这样的问题,做一下笔记.希望对自己和读者都有帮助. 在aap.con ...

  6. asp.net core 基于角色的认证登陆

    一.登陆页面的Controller [Authorize(Roles = "Admin,SuperAdmin")] public class ManageController : ...

  7. DDR3初识

    DDR3初识 选择2:1 ratio 意味用户总线宽度为DDR物理数据接口宽度的4倍.

  8. OutOfMemoryError异常java内存泄漏(Memory Leak)和内存溢出(Memory Overflow)

    本篇文章理解源自于<深入理解java虚拟机>2.4章节 实战:OutOfMemoryError异常   在以下例子中,所有代码都可以抛出OutOfMemoryError异常,但是要区分到底 ...

  9. kafka命令大全

    kafka命令大全 http://orchome.com/454

  10. 关于分布式uuid的一点设想

    在一次公开课上,听别人讲过全局分布式uuid的设计,听过twitter的snowflake的设计.也听过,如果使用单独的计数器服务,不可能每次都保存当前计数器到文本,自己想到应该可以每隔一些数,例如1 ...