[转]Spring常用注解总结(2)


继续上一篇。下面开始介绍Spring的注解,并改造之前的代码。

1、@Autowired


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

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

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

<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    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
    ">

    <context:component-scan base-package="com.spring" />

    <bean id="zoo" class="com.spring.model.Zoo" />
    <bean id="tiger" class="com.spring.model.Tiger" />
    <bean id="monkey" class="com.spring.model.Monkey" />

</beans>


注意第13行,必须告诉spring一下,我要使用注解了。告诉的方式有很多,
是一种最简单的,spring会自动扫描xxx路径下的注解。
看到第15行,原来zoo里面应当注入两个属性,tiger、monkey,现在不需要注入了。再看下,Zoo.java也很方便,把getter/setter都可以去掉

package com.spring.model;

import org.springframework.beans.factory.annotation.Autowired;

public class Zoo {

    @Autowired
    private Tiger tiger;

    @Autowired
    private Monkey monkey;

    public String toString(){
        return tiger + "\n" + monkey;
    }

}


这里@Autowired注解的意思就是,当Spring发现@Autowired注解时,将自动在代码上下文中找到和其匹配的Bean(默认是类型匹配),并自动注入到相应的地方去。
有一个细节性的问题是,假如bean里面有两个property,Zoo.java里面又去掉了属性的getter/setter并使用@Autowired注解标注这两个属性那会怎么样?答案是Spring会按照xml优先的原则去Zoo.java中寻找这两个属性的getter/setter ,导致的结果就是初始化bean的报错。
OK,假设此时我们把.xml文件的16行、17行两行给去掉,再运行,会抛出异常:

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)}


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

package com.spring.model;

import org.springframework.beans.factory.annotation.Autowired;

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。


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


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

package com.spring.service;

public interface ICar {

    public String getCarName();
}


两个实现类:BMWCar和BenChiCar

package com.spring.service.impl;

import com.spring.service.ICar;

public class BMWCar implements ICar {

    @Override
    public String getCarName() {
        return "BMW car";
    }

}
package com.spring.service.impl;

import com.spring.service.ICar;

public class BenChiCar implements ICar {

    @Override
    public String getCarName() {
        return "BenChi car";
    }

}


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

package com.spring.model;

import org.springframework.beans.factory.annotation.Autowired;

import com.spring.service.ICar;

public class CarFactory {

    @Autowired
    private ICar car;

    public String toString(){
        return car.getCarName();
    }
}


配置文件:applicationContext2.xml(文件放在src目录下)

<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    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
    ">

    <context:component-scan base-package="com.spring" />

    <!-- Autowired注解配合Qualifier注解 -->
    <bean id="carFactory" class="com.spring.model.CarFactory" />
    <bean id="bmwCar" class="com.spring.service.impl.BMWCar" />
    <bean id="benchi" class="com.spring.service.impl.BenChiCar" />


测试方法:使用Junit测试,需要引用junit的jar包

package com.spring.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.model.CarFactory;

/**
 * Autowired注解配合Qualifier
 *
 */
public class testSpring {
    @Test
    public void test(){
        //读取配置文件
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext2.xml");
        CarFactory carFactory=(CarFactory) ctx.getBean("carFactory");
        System.out.print(carFactory.toString());
    }
}


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

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, benchi]
    at 

No unique bean of type [com.spring.service.ICar] is defined: expected single matching bean but found 2: [bmwCar, benchi]


出现这种情况通常有两种解决办法:
(1)、在配置文件中删除其中一个实现类,Spring会自动去base-package下寻找Car接口的实现类,发现Car接口只有一个实现类,便会直接引用这个实现类。
(2)、实现类就有多个该怎么办?此时可以使用@Qualifier注解来指定Bean的名称。
例如将调用接口注解需要哪个实现类,注入名为bmwCar的Bean。此时运行程序,成功打印出信息

package com.spring.model;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.spring.service.ICar;

public class CarFactory {

    @Autowired
    @Qualifier("bmwCar")
    private ICar car;

    public String toString(){
        return car.getCarName();
    }
}


3、@Resource


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

package com.spring.model;

import javax.annotation.Resource;

public class Zoo1 {

    @Resource(name="tiger")
    private Tiger tiger;

    @Resource(type=Monkey.class)
    private Monkey monkey;

    public String toString(){
        return tiger + "\n" + monkey;
    }
}


这是详细的用法,说一下@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。先看一下配置文件,当然是全部删除了:

<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    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
    ">

    <context:component-scan base-package="com.spring" />

</beans>


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


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class Zoo {

    @Autowired
    private Tiger tiger;
    @Autowired
    private Monkey monkey;

    @Override
    public String toString() {
        return "Zoo [tiger=" + tiger + ", monkey=" + monkey + "]";
    }
}


这样,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”,可以的。只需要在@Service定义bean的名称就可

package com.spring.model;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service("Zoo")
@Scope("prototype")
public class Zoo {

    @Autowired
    private Tiger tiger;
    @Autowired
    private Monkey monkey;

    @Override
    public String toString() {
        return "Zoo [tiger=" + tiger + ", monkey=" + monkey + "]";
    }
}


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


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值