什么是注解

传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop、事物,这么做有两个缺点:

1、如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大;如果按需求分开.xml文件,那么.xml文件又会非常多。总之这将导致配置文件的可读性与可维护性变得很低

2、在开发中在.java文件和.xml文件之间不断切换,是一件麻烦的事,同时这种思维上的不连贯也会降低开发的效率

为了解决这两个问题,Spring引入了注解,通过"@XXX"的方式,让注解与Java Bean紧密结合,既大大减少了配置文件的体积,又增加了Java Bean的可读性与内聚性。

本篇文章,讲讲最重要的三个Spring注解,[email protected]@[email protected][email protected]

不使用注解

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

public class Tiger 
{ 
    private String tigerName = "TigerKing"; 
     
    public String toString() { return "TigerName:" + tigerName; } }

再定义一个猴子:

public class Monkey 
{ 
    private String monkeyName = "MonkeyKing"; 
     
    public String toString() { return "MonkeyName:" + monkeyName; } }

定义一个动物园:

public class Zoo 
{ 
    private Tiger tiger; 
    private Monkey monkey; public void setTiger(Tiger tiger) { this.tiger = tiger; } public void setMonkey(Monkey monkey) { this.monkey = monkey; } public Tiger getTiger() { return tiger; } public Monkey getMonkey() { return monkey; } public String toString() { return tiger + "\n" + monkey; } }

spring的配置文件这么写:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd" default-autowire="byType"> <bean id="zoo" class="com.xrq.bean.Zoo" > <property name="tiger" ref="tiger" /> <property name="monkey" ref="monkey" /> </bean> <bean id="tiger" class="com.xrq.domain.Tiger" /> <bean id="monkey" class="com.xrq.domain.Monkey" /> </beans>

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

@Autowired

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

因此,[email protected],先看一下spring配置文件怎么写:

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

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

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

public class Zoo 
{ 
    @Autowired 
    private Tiger tiger; 
     
    @Autowired 
    private Monkey monkey; public String toString() { return tiger + "\n" + monkey; } }

[email protected][email protected],将自动在代码上下文中找到和其匹配(默认是类型匹配)的Bean,并自动注入到相应的地方去。

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

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

Exception in thread "main" 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.xrq.domain.Tiger com.xrq.bean.Zoo.ttiger; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xrq.domain.Tiger] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: [email protected](required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:835) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) at com.xrq.test.MyTest.main(MyTest.java:13) Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.xrq.domain.Tiger com.xrq.bean.Zoo.ttiger; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xrq.domain.Tiger] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: [email protected](required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:571) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) ... 13 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.xrq.domain.Tiger] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: [email protected](required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:543) ... 15 more

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

public class Zoo 
{ 
    @Autowired(required = false) 
    private Tiger tiger; @Autowired(required = false) private Monkey monkey; public String toString() { return tiger + "\n" + monkey; } }

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

@Autowired接口注入

上面的比较简单,我们只是简单注入一个Java类,那么如果有一个接口,有多个实现,Bean里引用的是接口名,又该怎么做呢?比如有一个Car接口:

public interface Car 
{ 
    public String carName(); 
}

两个实现类BMW和Benz:

@Service 
public class BMW implements Car 
{ 
    public String carName() { return "BMW car"; } }
@Service 
public class Benz implements Car 
{ 
    public String carName() { return "Benz car"; } }

写一个CarFactory,引用Car:

@Service 
public class CarFactory 
{ 
    @Autowired 
    private Car car; public String toString() { return car.carName(); } }

不用说,一定是报错的,Car接口有两个实现类,Spring并不知道应当引用哪个实现类。这种情况通常有两个解决办法:

1、删除其中一个实现类,Spring会自动去base-package下寻找Car接口的实现类,发现Car接口只有一个实现类,便会直接引用这个实现类

2、实现类就是有多个该怎么办?[email protected]

@Service 
public class CarFactory 
{ 
    @Autowired 
    @Qualifier("BMW") 
    private Car car; public String toString() { return car.carName(); } }

[email protected]括号里面的应当是Car接口实现类的类名,我之前试的时候一直以为是bean的名字,所以写了"bMW",结果一直报错。

@Resource

[email protected]@Autowired下面说,是因为它们作用非常相似,这个就简单说了,[email protected]@[email protected],直接写Zoo.java了:

@Service 
public class Zoo 
{ 
    @Resource(name = "tiger") 
    private Tiger tiger; @Resource(type = Monkey.class) private Monkey monkey; public String toString() { return tiger + "\n" + monkey; } }

这是详细一些的用法,[email protected]

[email protected],默认通过name属性去匹配bean,找不到再按type去匹配

2、指定了name或者type则根据指定的类型去匹配bean

3、指定了name和type则根据指定的name和type去匹配bean,任何一个不匹配都将报错

然后,[email protected]@Resource两个注解的区别:

[email protected],@Resource默认按照byName方式进行bean匹配

[email protected],@Resource是J2EE的注解,这个看一下导入注解的时候这两个注解的包名就一清二楚了

Spring属于第三方的,J2EE是Java自己的东西,因此,[email protected],以减少代码和Spring之间的耦合。

@Service

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

要继续简化,[email protected],当然是全部删除了:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <context:component-scan base-package="com.xrq" /> </beans>

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

@Service 
public class Zoo 
{ 
    @Autowired 
    private Tiger ttiger; @Autowired private Monkey mmonkey; public String toString() { return ttiger + "\n" + mmonkey; } }

这样,Zoo.java在Spring容器中存在的形式就是"zoo",即可以通过ApplicationContext的getBean("zoo")[email protected],其实做了两件事情:

1、声明Zoo.java是一个bean,这点很重要,因为Zoo.java是一个bean,[email protected]自动注入

2、Zoo.java在bean中的id是"zoo",即类名且首字母小写

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

@Service 
@Scope("prototype") 
public class Zoo 
{ 
    @Autowired 
    private Monkey monkey; @Autowired private Tiger tiger; public String toString() { return "MonkeyName:" + monkey + "\nTigerName:" + tiger; } }

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

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

补充细节

最后再补充一个我发现的细节。假如animal包下有Tiger、domain包下也有Tiger,[email protected][email protected]下的Tiger,程序运行的时候依然会报错。

细想,其实这很好理解,两个Tiger都使 [email protected],意味着两个Bean的名字都是"tiger",那么我在Zoo.java中自动装配的是哪个Tiger呢?不明确,因 此,Spring容器会抛出BeanDefinitionStoreException异常,Caused by:

Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'monkey' for bean class [com.xrq.domain.Monkey] conflicts with existing, non-compatible bean definition of same name and class [com.xrq.animal.Monkey]

发布评论
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

Spring3:AOP讲解
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。