spring注解相关知识

1.@Resource和@Autowired 的区别

@Resource的作用相当于@Autowired,只不过@Autowired按byType自动注入,而@Resource默认按 byName自 动注入罢了。@Resource有两个属性是比较重要的,分是name和type,Spring将@Resource注解的name属性解析为bean的 名字,而type属性则解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自 动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。
  @Resource装配顺序
  1. 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
  2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
  3. 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
  4. 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;

2.@autowired与@qualifer的使用区别备忘

使用@Autowired注释进行byType注入,如果需要byName(byName就是通过id去标识)注入,增加@Qualifier注释
@Qualifer如果没有的话, 报的错如下:
No unique bean of type [org.springframework.transaction.PlatformTransactionManager] is defined: expected single matching bean but found 2: [transactionManager, jmsTransactionManager]

原因:
比如配置文件中有二个bean.
<bean id="jmsTransactionManager"
        class="org.springframework.jms.connection.JmsTransactionManager">
        <property name="connectionFactory"
            ref="advancedConnectionFactory" />breast
    </bean>
<bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource">
            <ref bean="cpcDataSource" />
        </property>
    </bean>
表面看起来是不同类型的类,但是由于在*Service里面注入的属性类型是PlatformTransactionManager.由于上面的二个bean都实现了这个接jquery中ajax异步时序问题

口.这样@autowired时,由于是bytype注入,就不能识别.此时就需要再加上@qualifer通过id去识别.


而如果没有使用@Service的话,报错如下:
No unique bean of type ..... expected at least 1 matching bean

示例:

@Autowired
    public void init(@Qualifier("ddlibserveDataSource")DataSource dataSource){
        this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
    }

猜你喜欢

转载自haiziwoainixx.iteye.com/blog/1838084