spring 使用注解注入bean

学了两种使用注解注入bean的方式,按照网上提供的方法学习并整理的。


1、@Resource  2、@Autowired

首先要说明的是 spring的头文件,下面是一个比较全的头文件

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">


第一种使用介绍:

@Resource 默认是按照名称来装配注入的,只有当找不到与名称匹配的bean才会按照类型来装配注入;是由J2EE提供,可以减少系统对spring的依赖,建议使用  ,可以书写标注在字段或者该字段的setter方法之上。

bean配置:

<context:annotation-config />
<bean id="helloAction" class="com.hsx.struts.action.HelloAction" scope="prototype"></bean>
    <bean id="userService" class="com.hsx.struts.service.UserService" scope="prototype">
      <!--  <property name="sqlMapClient">
           <ref bean="sqlMapClient"/>
       </property> -->
    </bean>

扫描二维码关注公众号,回复: 3636134 查看本文章

Java代码配置

a、标注在字段上

 @Resource(name="userService")
    private UserService userService;
b、标注在setter方法上

 @Resource(name="userService")
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

说明:括号内 name="userService" 可以省去,系统会自动按照属性名寻找bean.如果配了name属性,系统会按照name所配的bean id 查找。放在 字段上时,set方法可以省去。

第二种使用介绍:

@Autowired:默认是按照类型装配注入的,如果想按照名称来转配注入,则需要结合@Qualifier一起使用;可以书写标注在字段或者该字段的setter方法之上。

bean配置:

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="helloAction" class="com.hsx.struts.action.HelloAction" scope="prototype"></bean>
<bean id="userService" class="com.hsx.struts.service.UserService" scope="prototype"></bean>

Java 代码配置:

 @Autowired
    private UserService userService;

或者:

 @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }


说明:@Autowired 放在 字段上时,set方法可以省去。

按照名称注入,bean按照上边即可。

Java代码配置:

@Autowired
    @Qualifier("userService")
    private UserService userServices;

或者 
 @Autowired
    public void setUserServices(@Qualifier("userService")UserService userService) {
        this.userServices = userService;
    }





       

猜你喜欢

转载自blog.csdn.net/haoshaoxing/article/details/46504529