zoukankan      html  css  js  c++  java
  • 反对抄袭 正解spring的@Autowired 不要相信网上的错误版本

    首先,最重要的, @Autowired的就是用来来消除 set ,get方法.


    有些介绍,如著名的马士兵,说要在set方法上进行注入.我当时就看不明白了,既然只取消了一个GET,这个@Autowired还有什么屁用.不是瞎折腾么.还要用@Qualifier来帮忙指定BEAN.

    如下:

    //	@Autowired
    //	public void setUserDAO(@Qualifier("userDAOImpl") UserDAO userDAO) {
    //		this.userDAO = userDAO;
    //	}


    后来自己试了一下,在SPRING2.5和3.0下,都不用这样.


    直接使用

    Autowired 即可
    	
    	@Autowired
    	private UserDAO userDAO;


    也不需要在applicationContext.xml中加入:

        <!-- 该 BeanPostProcessor 将自动对标注 @Autowired 的 Bean 进行注入 -->  
        <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>


    贴出我的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: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:annotation-config />
    	
      <bean id="userDAOImpl" class="com.bjsxt.dao.impl.UserDAOImpl">
      
      </bean>
      
    
    	
      <bean id="userService" class="com.bjsxt.service.UserService" >
    
      </bean>
    
      
    </beans>


    public class UserService {
    	
    	@Autowired
    	private UserDAO userDAO;  
    		
    	public void add(User user) {
    		userDAO.save(user);
    	}
    	
    //	@Autowired
    //	public void setUserDAO(@Qualifier("userDAOImpl") UserDAO userDAO) {
    //		this.userDAO = userDAO;
    //	}
    }
    public class UserServiceTest {
    
    	@Test
    	public void testAdd() throws Exception {
    		
    		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");	
    		UserService service = (UserService)ctx.getBean("userService");
    		service.add(new User());
    		
    		
    	}
    
    }
    




  • 相关阅读:
    将数据库dbcp连接池改为c3p0连接池(草稿,别点)
    java遍历set集合
    mybatis映射文件(转)
    java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
    redis通过json方案存取对象com.alibaba.fastjson.JSONException: syntax error, expect
    PL/SQL配置oracle客户端,登录远程数据库配置
    Weblogic部署项目三种方式
    Service具体解释(二):Service生命周期
    Coredata — 入门使用
    UML建模学习1:UML统一建模语言简单介绍
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3215010.html
Copyright © 2011-2022 走看看