Spring_构造注入

时间:2023-03-09 08:18:21
Spring_构造注入

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

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

项目要先添加spring支持;

  1. package com;
  2. public class Computer {
  3. private Host host;
  4. private Display display;
  5. //public Computer(){}
  6. public Computer(Host host, Display display) {
  7. this.host = host;
  8. this.display = display;
  9. }
  10. public void run() {
  11. System.out.println(host.run() + "; " + display.run());
  12. }
  13. /*public void setHost(Host host) {
  14. this.host = host;
  15. }
  16. public void setDisplay(Display display) {
  17. this.display = display;
  18. }*/
  19. }
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;
	}*/

}
  1. package com;
  2. public class Display {
  3. public String run(){
  4. return "我是显示器,我在运行";
  5. }
  6. }
Spring_构造注入
package com;

public class Display {
	public String run(){
		return "我是显示器,我在运行";
	}
}
  1. package com;
  2. public class Host {
  3. public String run() {
  4. return "我是主机,我在运行";
  5. }
  6. }
Spring_构造注入
package com;

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

}
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:p="http://www.springframework.org/schema/p"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
  7. <bean id="host" class="com.Host"></bean>
  8. <bean id="display" class="com.Display"></bean>
  9. <bean id="computer" class="com.Computer">
  10. <!--要有默认构造方法,和属性的set方法-->
  11. <!-- <property name="host" ref="host"></property>
  12. <property name="display" ref="display"></property> -->
  13. <constructor-arg name="host" ref="host"/>
  14. <!-- 用另外一种,两种配置 -->
  15. <constructor-arg index="1">
  16. <ref bean="display"/>
  17. </constructor-arg>
  18. </bean>
  19. </beans>
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: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

  1. package com;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. public class TestComputer {
  6. @Test
  7. public void testRun(){
  8. ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml");
  9. Computer computer = (Computer) ac.getBean("computer");
  10. computer.run();
  11. }
  12. }
Spring_构造注入
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以后没有了;

  1. package com;
  2. public class Computer {
  3. private Host host;
  4. private Display display;
  5. public Computer(){}
  6. public Computer(Host host, Display display) {
  7. this.host = host;
  8. this.display = display;
  9. }
  10. public void run() {
  11. System.out.println(host.run() + "; " + display.run());
  12. }
  13. public void setHost(Host host) {
  14. this.host = host;
  15. }
  16. public void setDisplay(Display display) {
  17. this.display = display;
  18. }
  19. }
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;
	}

}
  1. package com;
  2. public class Display {
  3. public String run(){
  4. return "我是显示器,我在运行";
  5. }
  6. }
Spring_构造注入
package com;

public class Display {
	public String run(){
		return "我是显示器,我在运行";
	}
}
  1. package com;
  2. public class Host {
  3. public String run() {
  4. return "我是主机,我在运行";
  5. }
  6. }
Spring_构造注入
package com;

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

}
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:p="http://www.springframework.org/schema/p"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
  7. default-autowire="byName"
  8. >
  9. <!-- 第一种 :上面的 default-autowire="byName" 全局的,在beans上配置 -->
  10. <!-- 第二种:autowire="byName" 方式 -->
  11. <bean id="host" class="com.Host"></bean><!--autowire="byName"名字必须是host -->
  12. <bean id="display" class="com.Display"></bean>
  13. <bean id="computer" class="com.Computer" autowire="byName">
  14. <!-- 第二种:autowire="byType" 方式
  15. <bean id="host1" class="com.Host"></bean>
  16. <bean id="display1" class="com.Display"></bean>
  17. <bean id="computer" class="com.Computer" autowire="byType">
  18. -->
  19. <!--使用自动装配 这个不用
  20. <property name="host" ref="host"></property> -->
  21. </bean>
  22. </beans>
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: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>
  1. package com;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. public class TestComputer {
  6. @Test
  7. public void testRun(){
  8. ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml");
  9. Computer computer = (Computer) ac.getBean("computer");
  10. computer.run();
  11. }
  12. }
Spring_构造注入
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"/>方式

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:p="http://www.springframework.org/schema/p"
  5. xmlns:tx="http://www.springframework.org/schema/tx"
  6. xmlns:aop="http://www.springframework.org/schema/aop"
  7. xmlns:context="http://www.springframework.org/schema/context"
  8. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  9. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  10. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  11. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
  12. ">
  13. <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  14. <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
  15. </bean>
  16. <!-- 配置事务管理器 -->
  17. <bean id="txManage" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
  18. <property name="sessionFactory" ref="sessionFactory"></property>
  19. </bean>
  20. <!-- 要被事务管理(支持)的方法 -->
  21. <tx:advice id="txAdvice" transaction-manager="txManage">
  22. <tx:attributes >
  23. <!-- 默认false;propagation="REQUIRED":hibernate4的时候必须要使用 REQUIRED-->
  24. <tx:method name="get*" read-only="true" propagation="REQUIRED"/>
  25. <tx:method name="search*" read-only="true" propagation="REQUIRED"/>
  26. <tx:method name="find*" read-only="true" propagation="REQUIRED"/>
  27. <tx:method name="query*" read-only="true" propagation="REQUIRED"/>
  28. <tx:method name="*" rollback-for="DataAccessException" propagation="REQUIRED"/> <!-- 读写 -->
  29. </tx:attributes>
  30. </tx:advice>
  31. <!-- 切到类里面去(事务要加到哪里,一般在业务里面) -->
  32. <aop:config>
  33. <!--execution:切面要在哪里切,(* com.jboa.*.*(..)):com.jboa.service下所以的类,所以的方法,所以的返回值,都受到切面的影响 -->
  34. <aop:pointcut expression="execution(* com.jboa.service.*.*(..))" id="serviceMethods"/>
  35. <!-- 注释掉,就没事务了 -->
  36. <aop:advisor pointcut-ref="serviceMethods" advice-ref="txAdvice"/>
  37. </aop:config>
  38. <!-- 拆分配置文件:到新建 DaoApplicationContext.xml-->
  39. <!-- <bean id="accountDao" class="com.jboa.dao.impl.AccountDaoImpl" depends-on="sessionFactory">
  40. <property name="sessionFactory" ref="sessionFactory"></property>
  41. </bean>
  42. <bean id="employeeDao" class="com.jboa.dao.impl.EmployeeDaoImpl" depends-on="sessionFactory">
  43. <property name="sessionFactory" ref="sessionFactory"></property>
  44. </bean>
  45. <bean id="dictionaryDao" class="com.jboa.dao.impl.DictionaryDaoImpl" depends-on="sessionFactory">
  46. <property name="sessionFactory" ref="sessionFactory"></property>
  47. </bean> -->
  48. <!-- 拆分配置文件:到新建 ServiceApplicationContext.xml-->
  49. <!-- <bean id="employeeService" class="com.jboa.service.impl.EmployeeServiceImpl">
  50. <property name="employeeDao" ref="employeeDao"></property>
  51. </bean>
  52. <bean id="dictionaryService" class="com.jboa.service.impl.DictionaryServiceImpl">
  53. <property name="dictionaryDao" ref="dictionaryDao"></property>
  54. </bean> -->
  55. <!-- 拆分配置文件:到新建 ActionApplicationContext.xml-->
  56. <!-- <bean id="employeeAction" class="com.jboa.action.EmployeeAction" scope="prototype">
  57. <property name="employeeService" ref="employeeService"></property>
  58. <property name="dictionaryService" ref="dictionaryService"></property>
  59. </bean> -->
  60. <!-- 第二种方式 -->
  61. <!-- <import resource="DaoApplicationContext.xml"/>
  62. <import resource="ServiceApplicationContext.xml"/>
  63. <import resource="ActionApplicationContext.xml"/> -->
  64. </beans>
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: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

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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
  3. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  4. <display-name></display-name>
  5. <welcome-file-list>
  6. <welcome-file>login.jsp</welcome-file>
  7. </welcome-file-list>
  8. <!-- 整合Spring -->
  9. <context-param>
  10. <param-name>contextConfigLocation</param-name>
  11. <!-- 第一种拆分方式 -->
  12. <param-value>classpath:*ApplicationContext.xml</param-value>
  13. <!-- 第二种拆分方式 -->
  14. <!-- <param-value>classpath:DefaultApplicationContext.xml</param-value> -->
  15. </context-param>
  16. <listener>
  17. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  18. </listener>
  19. <!-- 配置strut2的过滤器 -->
  20. <filter>
  21. <filter-name>struts2</filter-name>
  22. <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  23. </filter>
  24. <filter-mapping>
  25. <filter-name>struts2</filter-name>
  26. <url-pattern>/*</url-pattern>
  27. </filter-mapping>
  28. </web-app>
Spring_构造注入
<?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>

然后执行测试类测试:

  1. package com.jboa.service;
  2. import org.junit.Test;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;
  5. import com.jboa.model.Department;
  6. import com.jboa.model.Employee;
  7. import com.jboa.model.Postion;
  8. public class EmployeeServiceTest {
  9. @Test
  10. public void testAdd() {
  11. ApplicationContext ac = new ClassPathXmlApplicationContext("/*ApplicationContext.xml");
  12. EmployeeService employeeService = (EmployeeService) ac.getBean("employeeService");
  13. Employee employee = new Employee();
  14. employee.setSn("user111111");
  15. employee.setPassword("user111111");
  16. employee.setStatus("1");
  17. employee.setName("user111111");
  18. Postion p = new Postion();
  19. p.setId(2);
  20. employee.setPostion(p);
  21. Department d = new Department();
  22. d.setId(1);
  23. employee.setDepartment(d);
  24. employeeService.add(employee);
  25. }
  26. }