Spring学习基础(二):Spring注解之Bean的注入与声明

为什么要使用Spring注解?让我们先来了解一下不使用注解的例子

  • 创建老虎类
package com.spring.model;
public class Tiger {
   private String tigerName="TigerKing";
   public String toString(){
       return "TigerName:"+tigerName;
   }
}
  • 创建猴子类
package com.spring.model;
public class Monkey {
    private String monkeyName = "MonkeyKing";
    public String toString(){
        return "MonkeyName:" + monkeyName;
    }
}
  • 创建动物园类
package com.spring.model;
public class Zoo {
    private Tiger tiger;
    private Monkey monkey;
    public Tiger getTiger() {
        return tiger;
    }
    public void setTiger(Tiger tiger) {
        this.tiger = tiger;
    }
    public Monkey getMonkey() {
        return monkey;
    }
    public void setMonkey(Monkey monkey) {
        this.monkey = monkey;
    }
    public String toString(){
        return tiger + "\n" + monkey;
    }
}
  • 配置文件中定义Bean
<?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
    ">
    
     <bean id="zoo" class="com.spring.model.Zoo" >
        <property name="tiger" ref="tiger" />
        <property name="monkey" ref="monkey" />
    </bean>
    
    <bean id="tiger" class="com.spring.model.Tiger" />
    <bean id="monkey" class="com.spring.model.Monkey" />
</beans>
  • 编写测试类
public class TestAnnotation {
    /**
     * 不使用注解
     */
    @Test
    public void test(){
        //读取配置文件
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext2.xml");
        Zoo zoo=(Zoo) ctx.getBean("zoo");
        System.out.println(zoo.toString());
    }
}

以上是不使用注解编写的程序,下面将会就不同功能的注解对代码进行优化。

Spring常用注解如下表:

注入注解解释
@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初始化注解

本章主要研究Bean的注入注解与声明注解,具体如下:

注解解释方式
@Service用于标注业务层组件声明注解
@Controller用于标注控制层组件(如struts中的action)声明注解
@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。声明注解
@Repository用于标注数据访问组件,即DAO组件。声明注解
@Autowired默认按类型装配,如果我们想使用按名称装配,可以结合@Qualifier注解一起使用。如下:注入注解
@Autowired@Qualifier(“personDaoBean”) 存在多个实例配合使用注入注解
@Resource默认按名称装配,当找不到与名称匹配的bean才会按类型装配。注入注解

下面我们举一个例子分别了解这些注解:

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>

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

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

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

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

package com.spring.service;
public interface ICar {
    
    public String getCarName();
}

两个实现类BMWCar和BenzCar:

package com.spring.service.impl;
import com.spring.service.ICar;
public class BMWCar implements ICar{
    
    public String getCarName(){
        return "BMW car";
    }
}
package com.spring.service.impl;
import com.spring.service.ICar;
public class BenzCar implements ICar{
    
    public String getCarName(){
        return "Benz 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();
    }
    
}

配置文件:

<?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="benz" class="com.spring.service.impl.BenzCar" />
    </beans>

测试方法:

/**
 * Autowired注解配合Qualifier注解
 */
@Testpublic void test1(){
    //读取配置文件
    ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext2.xml");
    CarFactory carFactory=(CarFactory) ctx.getBean("carFactory");
    System.out.println(carFactory.toString());
}

运行一下,报错。Car接口有两个实现类,Spring并不知道应当引用哪个实现类。
出现这种情况通常有两种解决办法:
(1)、在配置文件中删除其中一个实现类,Spring会自动去base-package下寻找Car接口的实现类,发现Car接口只有一个实现类,便会直接引用这个实现类。
(2)、实现类就是有多个该怎么办?此时可以使用@Qualifier注解来指定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();
    }
    
}

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

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>

这样,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",即类名且首字母小写。

package com.spring.model;
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;

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

修改注解名:
@Service(“Zoo”)
@Scope(“prototype”)public class Zoo {
@Scope注解,应该很好理解。因为Spring默认产生的bean是单例的,假如我不想使用单例怎么办,xml文件里面可以在bean里面配置scope属性。注解也是一样,配置@Scope即可,默认是"singleton"即单例,"prototype"表示原型即每次都会new一个新的出来。
在base-package指明一个包
<context:component-scan base-package=“cn.gacl.java”/>
表明cn.gacl.java包及其子包中,如果某个类的头上带有特定的注解【@Component/@Repository/@Service/@Controller】,就会将这个对象作为Bean注册进Spring容器。也可以在<context:component-scan base-package=” ”/>中指定多个包,如:
<context:component-scan base-package=“cn.gacl.dao.impl,cn.gacl.service.impl,cn.gacl.action”/>

5、@Controller

@Controller对应表现层的Bean,也就是Action,例如:
@Controller
@Scope(“prototype”)public class UserAction extends BaseAction{

6、@Service

@Service对应的是业务层Bean,例如:
@Service(“userService”)
public class UserServiceImpl implements 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就主动注入给他。

7.@ Repository

@Repository对应数据访问层Bean ,例如:
@Repository(value=“userDao”)public class UserDaoImpl extends BaseDaoImpl {
@Repository(value=“userDao”)注解是告诉Spring,让Spring创建一个名字叫"userDao"的UserDaoImpl实例。
当Service需要使用Spring创建的名字叫"userDao"的UserDaoImpl实例时,就可以使用@Resource(name = “userDao”)注解告诉Spring,Spring把创建好的userDao注入给Service即可。
// 注入userDao,从数据库中根据用户Id取出指定用户时需要用到
@Resource(name = “userDao”)private BaseDao userDao;

加油!!!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喜狼狼与灰太杨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值