2014-05-16 09:01:08上课内容:

依赖注入的第二种注入方式:构造器注入

创建带参数的构造方法,参数类型为注入类的类型

项目要先添加Spring支持;

package com;

public class Computer {
	private Host host;
	private Display display;

	//public Computer(){}
	public Computer(Host host, Display display) {
		this.host = host;
		this.display = display;
	}

	public void run() {
		System.out.println(host.run() + "; " + display.run());
	}
	/*public void setHost(Host host) {
		this.host = host;
	}
	public void setDisplay(Display display) {
		this.display = display;
	}*/

}
package com;

public class Display {
	public String run(){
		return "我是显示器,我在运行";
	}
}
package com;

public class Host {
	public String run() {
		return "我是主机,我在运行";
	}

}
<?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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<bean id="host" class="com.Host"></bean>
	<bean id="display" class="com.Display"></bean>

	<bean id="computer" class="com.Computer">
		<!--要有默认构造方法,和属性的set方法-->
		<!-- <property name="host" ref="host"></property>
		<property name="display" ref="display"></property> -->

		<constructor-arg name="host" ref="host"/>
		<!-- 用另外一种,两种配置 -->
		<constructor-arg index="1">
			<ref bean="display"/>
		</constructor-arg>

	</bean>
</beans>

TestComputer

package com;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestComputer {
	@Test
	public void testRun(){
		ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml");
		Computer computer = (Computer) ac.getBean("computer");
		computer.run();
	}
}

自动装配:Spring可以自动根据属性类型、名称等进行注入

autowire属性可以设置为no、byType或byName

 

byName 一个都没找到,不报错;采用byName方式,将根据属性名称在Spring Bean Factory中找,找到即自动注入,否则,什么都不做

byType 找到一个以上报错;

Spring提供了依赖检查功能

default-dependency-check属性 spring3.0以后没有了;

package com;

public class Computer {
	private Host host;
	private Display display;

	public Computer(){}
	public Computer(Host host, Display display) {
		this.host = host;
		this.display = display;
	}

	public void run() {
		System.out.println(host.run() + "; " + display.run());
	}
	public void setHost(Host host) {
		this.host = host;
	}
	public void setDisplay(Display display) {
		this.display = display;
	}

}
package com;

public class Display {
	public String run(){
		return "我是显示器,我在运行";
	}
}
package com;

public class Host {
	public String run() {
		return "我是主机,我在运行";
	}

}
<?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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
	default-autowire="byName"
	>
	<!-- 第一种 :上面的 default-autowire="byName" 全局的,在beans上配置 -->

	<!-- 第二种:autowire="byName" 方式 -->
	<bean id="host" class="com.Host"></bean><!--autowire="byName"名字必须是host -->
	<bean id="display" class="com.Display"></bean>

	<bean id="computer" class="com.Computer" autowire="byName"> 

	<!-- 第二种:autowire="byType" 方式
	<bean id="host1" class="com.Host"></bean>
	<bean id="display1" class="com.Display"></bean>

	<bean id="computer" class="com.Computer" autowire="byType">
	-->

	<!--使用自动装配 这个不用
	 <property name="host" ref="host"></property> -->

	</bean>
</beans>
package com;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestComputer {
	@Test
	public void testRun(){
		ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml");
		Computer computer = (Computer) ac.getBean("computer");
		computer.run();
	}
}

拆分配置文件:

新建Dao Service Action的配置文件,修改web.xml使用通配符*;

测试类测试 EmployeeServiceTest  



拆分配置文件两种方法

1.配制Spring集成时:配制ContextLoadListener的contextConfigLocation属性,配置多个配置文件用,逗号隔开;或者使用通配符

2.在公用配置文件使用<import resource="x.xml"/>方式

<?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:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"
	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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
	 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
	 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
	  ">

	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
	</bean>

	<!-- 配置事务管理器 -->
	<bean id="txManage" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<!-- 要被事务管理(支持)的方法 -->
	<tx:advice id="txAdvice" transaction-manager="txManage">
		<tx:attributes >
			<!-- 默认false;propagation="REQUIRED":hibernate4的时候必须要使用 REQUIRED-->
			<tx:method name="get*" read-only="true" propagation="REQUIRED"/>
			<tx:method name="search*" read-only="true" propagation="REQUIRED"/>
			<tx:method name="find*" read-only="true" propagation="REQUIRED"/>
			<tx:method name="query*" read-only="true" propagation="REQUIRED"/>
			<tx:method name="*" rollback-for="DataAccessException" propagation="REQUIRED"/> <!-- 读写 -->
		</tx:attributes>
	</tx:advice>
	<!-- 切到类里面去(事务要加到哪里,一般在业务里面) -->
	<aop:config>
		<!--execution:切面要在哪里切,(* com.jboa.*.*(..)):com.jboa.service下所以的类,所以的方法,所以的返回值,都受到切面的影响 -->
		<aop:pointcut expression="execution(* com.jboa.service.*.*(..))" id="serviceMethods"/>
		<!-- 注释掉,就没事务了 -->
        <aop:advisor pointcut-ref="serviceMethods" advice-ref="txAdvice"/>
	</aop:config>
	<!-- 拆分配置文件:到新建 DaoApplicationContext.xml-->
	<!-- <bean id="accountDao" class="com.jboa.dao.impl.AccountDaoImpl" depends-on="sessionFactory">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<bean id="employeeDao" class="com.jboa.dao.impl.EmployeeDaoImpl" depends-on="sessionFactory">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	<bean id="dictionaryDao" class="com.jboa.dao.impl.DictionaryDaoImpl" depends-on="sessionFactory">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean> -->
	<!-- 拆分配置文件:到新建 ServiceApplicationContext.xml-->
	<!-- <bean id="employeeService" class="com.jboa.service.impl.EmployeeServiceImpl">
		<property name="employeeDao" ref="employeeDao"></property>
	</bean>
	<bean id="dictionaryService" class="com.jboa.service.impl.DictionaryServiceImpl">
		<property name="dictionaryDao" ref="dictionaryDao"></property>
	</bean> -->
	<!-- 拆分配置文件:到新建 ActionApplicationContext.xml-->
	<!-- <bean id="employeeAction" class="com.jboa.action.EmployeeAction" scope="prototype">
		<property name="employeeService" ref="employeeService"></property>
		<property name="dictionaryService" ref="dictionaryService"></property>
	</bean> -->
	<!-- 第二种方式 -->
	<!-- <import resource="DaoApplicationContext.xml"/>
	<import resource="ServiceApplicationContext.xml"/>
	<import resource="ActionApplicationContext.xml"/> -->
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	<display-name></display-name>
	<welcome-file-list>
		<welcome-file>login.jsp</welcome-file>
	</welcome-file-list>
	<!-- 整合Spring -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<!-- 第一种拆分方式 -->
		<param-value>classpath:*ApplicationContext.xml</param-value>
		<!-- 第二种拆分方式 -->
		<!-- <param-value>classpath:DefaultApplicationContext.xml</param-value> -->
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 配置strut2的过滤器 -->
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

然后执行测试类测试:

package com.jboa.service;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.jboa.model.Department;
import com.jboa.model.Employee;
import com.jboa.model.Postion;

public class EmployeeServiceTest {
	@Test
	public void testAdd() {
		ApplicationContext ac = new ClassPathXmlApplicationContext("/*ApplicationContext.xml");
		EmployeeService employeeService = (EmployeeService) ac.getBean("employeeService");
		Employee employee = new Employee();
		employee.setSn("user111111");
		employee.setPassword("user111111");
		employee.setStatus("1");
		employee.setName("user111111");
		Postion p = new Postion();
		p.setId(2);
		employee.setPostion(p);
		Department d = new Department();
		d.setId(1);
		employee.setDepartment(d);
		employeeService.add(employee);
	}
}

Spring配置优化_构造器注入+自动装配的更多相关文章

  1. Spring(九):Spring配置Bean(二)自动装配的模式、Bean之间的关系

    XML配置里的Bean自动装配 Spring IOC容器可以自动装配Bean,需要做的仅仅是在<bean>的autowire属性里指定自动装配的模式,模式包含:byType,byName, ...

  2. spring实战四之Bean的自动装配(注解方式)

    使用注解装配: 从spring2.5开始,Spring启用了使用注解自动装配Bean的属性,使用注解方式自动装配与在XML中使用 autowire 属性自动装配并没有太大区别,但是使用注解方式允许更细 ...

  3. spring框架学习(四)自动装配

    set注入和构造注入有时在做配置时比较麻烦.所以框架为了提高开发效率,提供自动装配功能,简化配置.spring框架式默认不支持自动装配的,要想使用自动装配需要修改spring配置文件中<bean ...

  4. spring实战二之Bean的自动装配(非注解方式)

    Bean的自动装配 自动装配(autowiring)有助于减少甚至消除配置<property>元素和<constructor-arg>元素,让Spring自动识别如何装配Bea ...

  5. Spring Bean 注入 1 - 构造方法注入,属性注入,自动装配

    1.代码结构图 xxx 2.bean代码 package com.xxx.bean; /** * Created with IntelliJ IDEA. * User: zhenwei.liu * D ...

  6. Spring - bean的autowire属性(自动装配)

    当我们要往一个bean的某个属性里注入另外一个bean,我们会使用<property> + <ref/>标签的形式.但是对于大型项目,假设有一个bean A被多个bean引用注 ...

  7. Spring -- 入门,装备集合,自动装配,分散装配,自定义编辑器

    1. 概要 struts2:web hibernate:持久化 spring:业务层.管理bean的,容器.List Map Set. 体验spring: 1.创建java项目. 2.引入spring ...

  8. Spring学习03(Bean的自动装配)

    6.Bean的自动装配 6.1 自动装配说明 自动装配是使用spring满足bean依赖的一种方法 spring会在应用上下文中为某个bean寻找其依赖的bean. Spring中bean的三种装配机 ...

  9. spring为什么推荐使用构造器注入?

    闲谈 ​ Spring框架对Java开发的重要性不言而喻,其核心特性就是IOC(Inversion of Control, 控制反转)和AOP,平时使用最多的就是其中的IOC,我们通过将组件交由Spr ...

随机推荐

  1. ●BZOJ 3996 [TJOI2015]线性代数

    题链: http://www.lydsy.com/JudgeOnline/problem.php?id=3996 题解: 好题啊.(不太熟悉矩阵相关,所以按某些博主的模型转换来理解的)首先,那个式子可 ...

  2. JS按照指定的周期来调用函数方法

    setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式. setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭.由 s ...

  3. Python作业之购物车

    作业之购物车 购物车的要求如下: 输入总金额 选择购买的商品,金额足够时,把选择的商品添加到购物车,金额不足时,进行提示,商品将不会添加到购物车 随时可以退出程序,同时输出已购买的商品 具体代码如下: ...

  4. C语言程序设计预报作业

    1. 阅读邹欣老师的博客--师生关系,针对文中的几种师生关系谈谈你的看法,你期望的师生关系是什么样的? 答:万物都是变化的,师生关系也一样.小学中学把老师看作春蚕,蜡烛的的比喻到了大学显然行不通了.大 ...

  5. SSD-Tensorflow: 3 步运行 TensorFlow 单图片多盒目标检测器

    昨天类似的 YOLO: https://www.v2ex.com/t/392671#reply0 下载这个项目 https://github.com/balancap/SSD-Tensorflow 解 ...

  6. mysql获取某个表的所有字段名

    http://www.netingcn.com/mysql-column-name.html mysql安装成功后可以看到已经存在mysql.information_schema和test这个几个数据 ...

  7. Git/GitHub SSH配置

    生成 SSH 公钥 如前所述,许多 Git 服务器都使用 SSH 公钥进行认证. 为了向 Git 服务器提供 SSH 公钥,如果某系统用户尚未拥有密钥,必须事先为其生成一份. 这个过程在所有操作系统上 ...

  8. Android studio安装和问题

    一.Android studio的安装 [提示]A.以下Android studio2.2.2版本.(也有新版本) B.以下是用Android studio自带的sdk ①双击安装文件进行安装 ②如果 ...

  9. List Set Map比较

    List按对象进入的顺序保存对象,不做排序或编辑操作. Set对每个对象只接受一次,并使用自己内部的排序方法(通常,你只关心某个元素是否属于Set,而不关心它的顺序–否则应该使用List). Map同 ...

  10. Java并发编程(一)-为什么要并发

    并发所带来的好处 1. 并发在某些情况(并不是所有情况)下可以带来性能上的提升 1) 提升对CPU的使用效率 提升多核CPU的利用率:一般来说一台主机上的会有多个CPU核心,我们可以创建多个线程,理论 ...