Spring@Autowired注解与省去get和set方法,对注解Autowired放在setter方法上的情况

<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:websocket="http://www.springframework.org/schema/websocket"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd
		http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.3.xsd">


         <bean id="autotest" class="autotest" autowire="constructor">  
            
         </bean>
         
         <!-- 
         当 Spring 容器启动时,AutowiredAnnotationBeanPostProcessor 将扫描 Spring 容器中所有 Bean,当发现 Bean 中拥有 @Autowired 注释时就找到和其匹配(默认按类型匹配)的 Bean,并注入到对应的地方中去
          -->
         <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
        
          <bean id="person" class="Person">  
            <property name="age" value="21"></property>  
            <property name="name" value="李跃"></property>  
             <property name="sex" value="男"></property>  
         </bean>  

  
</beans>

 

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class autotest {  
          
     @Autowired//这里用了这个注释就省去了构造方法或者get,set方法来设置person属性  
    private Person person;
     
  

	public void fun(){  
           ConfigurableApplicationContext cf=new ClassPathXmlApplicationContext("spring-mvc.xml");      
           autotest autotest=(autotest)cf.getBean("autotest");   
           System.out.println(autotest);  
           System.out.println(autotest.person);  
     }  
       
        public static void main(String args[]){  
            new autotest().fun();  
        }  
}  


否则如下

 

 

<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:websocket="http://www.springframework.org/schema/websocket"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd
		http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.3.xsd">


         <bean id="autotest" class="autotest" >  
            <property name="person" ref="person"></property>  
         </bean>
         
      
          <bean id="person" class="Person">  
            <property name="age" value="21"></property>  
            <property name="name" value="李跃"></property>  
             <property name="sex" value="男"></property>  
         </bean>  

  
</beans>

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class autotest {  
          
    
    private Person person;
     
    public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public void fun(){  
           ConfigurableApplicationContext cf=new ClassPathXmlApplicationContext("spring-mvc.xml");      
           autotest autotest=(autotest)cf.getBean("autotest");   
           System.out.println(autotest);  
           System.out.println(autotest.person);  
     }  
       
        public static void main(String args[]){  
            new autotest().fun();  
        }  
}  

 

 

 

 

 

2.对注解Autowired放在setter方法上的情况,这种情况要注意几种情况,先看代码

 

<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:websocket="http://www.springframework.org/schema/websocket"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd
		http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket-4.3.xsd">


         <bean id="autotest" class="autotest"/>  
          
         <!-- 
                            当 Spring 容器启动时,AutowiredAnnotationBeanPostProcessor 将扫描 Spring 容器中所有 Bean,当发现 Bean 中拥有 @Autowired 注释时就找到和其匹配(默认按类型匹配)的 Bean,并注入到对应的地方中去
          -->
        <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
         
         <bean id="person" class="Person">  
             <property name="age" value="21"></property>  
             <property name="name" value="李跃"></property>  
             <property name="sex" value="男"></property>  
         </bean>  

  
</beans>

 

 

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

//A:
public class Autotest{  
//C:    
private Person person;
	
	public void fun(){  
           ConfigurableApplicationContext cf=new ClassPathXmlApplicationContext("spring-mvc.xml");      
           Autotest autotest=(Autotest)cf.getBean("autotest");   
          
           System.out.println(autotest.person); //Person@4f970963
           System.out.println(this); //autotest@2f92e0f4
           System.out.println(autotest); //autotest@7b49cea0
           System.out.println(this.person);//null,
           
     }  
       
    public Person getPerson() {
    	System.out.println(person); 
		return person;
	}
    
    @Autowired
	public void setPerson(Person person) {
		this.person = person;
	}

   public static void main(String args[]){  
	       new Autotest().fun(); // (new Autotest()==B)调用A==b.a.fun() 
        }  
}  

 

 

 

上面要注意区分几个对象this,autotest,是有区别的,对this和autotest来说person都是他们的属性,但是真正通过注解和配置文件配合工作的却是autotest,所以对于注解在setter方法上的情况,只有autotest.person不是空,单独的this.person或者new 一个对象.person是空的。这里我是来自http://blog.csdn.net/badboy_qiao/article/details/52713257最后总结的启发。

 

 

结论:注入的对象,只会调用空参构造函数,且这个对象的所有属性都是默认值,自己手动赋予的值不会被使用,

 

所以在A中的C类,在B中调用A的时候,创建的A对象的属性都是默认值,所以A对象虽然有了,但是A的属性C却是null,所以在B中直接this.a.c.method()是会报null指针异常的,且是c是null的发生原因。

解决方式:C在A中添加get方法,然后B中使用a.getC()即可获得c的对象,且c的对象也是spring注入的。

 

再顺便谈一个问题做下记录,为了更好理解上面的几句话看下面对象的输出,this对象始终和第一次真正new出来的对象(Autotest test=new Autotest();不是new Autotest();)是同一个东西

 

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

//A:
public class autotest{  
//C:    
private Person person;
	
	public void fun(){  
           ConfigurableApplicationContext cf=new ClassPathXmlApplicationContext("spring-mvc.xml");      
           autotest autotest=(autotest)cf.getBean("autotest");   
           autotest test=new autotest();
           System.out.println(test);//D autotest@7b49cea0 
           System.out.println(this); //C autotest@28a418fc
           System.out.println(this.person);//null
           System.out.println(test.person);//null
           System.out.println(autotest.person);//Person@887af79
     }  
       
    public Person getPerson() {
    	System.out.println(person); 
		return person;
	}
    
    @Autowired
	public void setPerson(Person person) {
		this.person = person;
	}

   public static void main(String args[]){ 
	      System.out.println(new autotest());//B autotest@2f92e0f4
	      autotest test=new autotest();
	      System.out.println(test.person);//null
	      System.out.println(test);//A autotest@28a418fc
	      test.fun(); 
        }  
}  

 

 

 

 

 

还有一个地方就是如果所有bean在容器中已经存在,那么我们某个Java类中如果用到其它对象,我们可以省去在当前这个Java类的bean配置文件中用property来配置它包含的属性,它会自动注入这些属性对象,直接使用就行。

如下面这里使用到这个对象

 

这个类的bean中可以直接

<bean name="shopManagerController" class="com.xxxx.ShopManagerController"">

</bean>不用在controller的bean的property配置shopManagerService,可以省去,用了resource注解settter方法也可以省去,但是要在接口实现类或者类的上面使用@Service("resource右边的name或者接口或者类的首字母小写")

 

<!-- 把标记了@Controller等注解的类转换为bean -->
<context:component-scan base-package="com.XXX" />

XML中也不需要配置controller的bean

 

这就是spring中依赖注入的思想,通过添加自动扫描包和对应类上添加注解,那么对象的创建和依赖都由spring去帮助我们完成。

 

1.bean的懒加载,个人理解

1.通过自动扫包,注解方式配置bean,不用繁琐的在xml文件中进行配置很多bean,
这种bean当tomcat启动项目的时候,bean对象是null,当我调用相应方法时,
它会首先被实例化然后被调用,如下面只有当我我调用selectpage方法时,handle通过afterPropertiesSet方法调用子类的
的initService方法被实例化,然后handle对象不再为空


protected abstract void initService();


@Override
public void afterPropertiesSet() throws Exception {
initService();
System.out.println("初始化handle"+handle);
if (handle == null) {
logger.info("Generic handle is not set. Please set it in the initService method if handle access is desired!");
}


}




public SearchCriteria<T> selectPage(SearchCriteria<T> sc) {
return handle.selectPage(sc);
}




2.xml中配置bean,这种bean当tomcat启动项目的时候,bean对象就被实例化放入到一个容器中,当我调用相应方法时,
它会被直接取出来,如上面当我我调用selectpage方法时,不需要再进行afterPropertiesSet方法调用子类的
的initService方法对handle进行实例化,然后handle对象不会为空。

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
使用中文解释ssm管理系统文件action文件里的以下代码package com.action; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.entity.Marks; import com.entity.Programs; import com.entity.Student; import com.entity.Teacher; import com.service.MarksService; import com.service.ProgramsService; import com.service.StudentService; import com.service.TeacherService; import com.util.PageHelper; import com.util.VeDate; //定义为控制器 @Controller // 设置路径 @RequestMapping(value = "/marks", produces = "text/plain;charset=utf-8") public class MarksAction extends BaseAction { // 注入Service 由于标签的存在 所以不需要getter setter @Autowired @Resource private MarksService marksService; @Autowired @Resource private TeacherService teacherService; @Autowired @Resource private StudentService studentService; @Autowired @Resource private ProgramsService programsService; // 准备添加数据 @RequestMapping("createMarks.action") public String createMarks() { List<Student> studentList = this.studentService.getAllStudent(); this.getRequest().setAttribute("studentList", studentList); List<Programs> programsList = this.programsService.getAllPrograms(); this.getRequest().setAttribute("programsList", programsList); return "addmarks"; } // 添加数据 @RequestMapping("addMarks.action") public String addMarks(Marks marks) { double total = 0; List<Programs> programsList = this.programsService.getAllPrograms(); for (Programs p : programsList) { String pnum = this.getRequest().getParameter("num_" + p.getProgramsid()); System.out.println(pnum); total += Double.parseDouble(pnum); } String teacherid = (String) this.getSession().getAttribute("teacherid"); marks.setTeacherid(teacherid); marks.setAddtime(VeDate.getStringDateShort()); marks.setScore("" + VeDate.getDouble(total)); this.marksService.insertMarks(marks); return "redirect:/marks/createMarks.action"; }
05-05
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值