Spring配置優化_構造器注入+自動裝配
依賴注入的第二種注入方式:構造器注入
建立帶引數的構造方法,引數型別為注入類的型別
專案要先新增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
自動裝配: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(); } }
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配置優化_構造器注入+自動裝配
2014-05-16 09:01:08上課內容: 依賴注入的第二種注入方式:構造器注入 建立帶引數的構造方法,引數型別為注入類的型別 專案要先新增Spring支援; package com; public class Computer { private Host h
深入學習Spring框架之二構造器注入方式裝配Bean
這一節我們來看看怎麼使用Spring建立我們的Bean物件。 容器是Spring的核心,Spring的容器有兩種型別:Bean工廠,由BeanFactory介面定義,是最簡單的容器;以及應用上下文,由ApplicationContext定義。Bean工廠對於
【Spring】淺談spring為什麼推薦使用構造器注入
一、前言 Spring框架對Java開發的重要性不言而喻,其核心特性就是IOC(Inversion of Control, 控制反轉)和AOP,平時使用最多的就是其中的IOC,我們通過將元件交由Spring的IOC容器管理,將物件的依賴關係由Spring控制,避免硬編碼所造成的過度程式耦合。
Spring 五、使用構造器注入:實現constructor-arg標籤注入ConstructorArgument
第四周: 實現建構函式注入 引入ConstructorArgument 如何找到合適的構造器: ConstructorResolver //petstore-v3.xml <bean id="petStore" class="org.litesp
Spring注入:配置注入(set注入和構造器注入)與註解注入
轉自:http://blog.csdn.net/u011579138/article/details/51379066 注入簡介 Spring注入可以理解為是對一個物件進行初始化,也就是省去new的這個步驟,類似於工廠模式一樣,通過一個工廠製造出這個物件,如果遇到修
【spring學習-day2】IOC-DI-scope-setter和構造器注入
【補充】 這是早就寫了的文章,如今有新的理解,想補充完成。 1.scope 2.IOC 3.DI 4.setter注入和構造器注入 5.init和destory 【打頭說明】 IOC說的是控制反轉,意思就是讓spring來建立物件,竟然讓spring來建立物件
spring基於 XML 構造器注入
值傳遞 <constructor-arg value="value"> </constructor-arg> 引用Bean <constructor-arg ref
spring IOC構造器注入使用
執行主類 package com.beans; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicati
spring IOC一個類有多個構造器,用構造器注入怎麼解決匹配問題
Car 類寫入兩個構造器(引數不同) package com.beans; public class Car { private String brand; private String corp; private double price
Spring的《XML顯式裝配bean》之通過構造器注入Bean
本文主要講解兩點: 1.怎麼樣宣告一個bean 2.通過構造器注入bean 1. 怎麼樣宣告一個bean? 1) 建立一個類: package spring.ch1.topic5; public class Song {
Spring容器框架、spring ioc、兩種注入方法set注入與構造器注入
#1>spring是什麼? spring是一個輕量級的控制反轉(IoC)和麵向切面(AOP)的容器框架 ——從大小與開銷兩方面而言Spring都是輕量的 ——通過控制反轉(IOC)的技術達到鬆耦合的目的 ——提供了面向切面程式設計的豐富支援,允許通過分離應用的業務
Spring IOC三種注入方式(介面注入、setter注入、構造器注入)
IOC ,全稱 (Inverse Of Control) ,中文意思為:控制反轉, Spring框架的核心基於控制反轉原理。 什麼是控制反轉? 控制反轉是一種將元件依賴關係的建立和管理置於程式外部的技術。 由容器控制程式之間的關係,而不是由程式碼直接控制 由於控制權由程式碼
spring的屬性注入和構造器注入
spring在向IOC容器中注入Bean的時候,有三種注入方式: 屬性注入 構造器注入 工廠方法注入 平常中用到的前兩種方法較多,下面對前兩種方法舉例。 一、屬性注入 1、建立一個car類,作為注入的bean package com.lzj
Java Web實戰04--Spring之屬性注入和構造器注入
和前面一樣,建立maven工程,然後進行以下操作過程, 1、新建一個bag類,設定四個欄位,如下所示: package com.yefeng.spring.spring2; /** * @au
spring注入bean兩種方式(屬性注入,構造器注入)
利用Spring的IOC實現簡單小程式,Spring推薦介面程式設計,這裡定義兩個介面:IDao,IService,以及它們的實現類IDaoImpl,IServiceImpl,程式碼如下: package DAO; public interface IDao {public
spring構造器注入
一、宣告一個簡單的bean 直接來個角色bean public class Roles { private int id; private String roleName; public Roles() { } public Roles(int id,St
Spring依賴註入構造器註入(通過構造函數註入)
ava import todo etag 管理 path 通過 ring classpath 在src目錄下建立applicationContext.xml (Spring 管理 bean的配置文件) <?xml version="1.0" encoding="
spring配置計劃任務管理器
service express BE erb pro pri frame span 日誌 <!-- 計劃任務管理器 --> <bean class="org.springframework.scheduling.quartz.SchedulerFacto
spring4構造器注入和@Resource,@Autowired的區別
為什麼要用spring4構造器注入 https://www.cnblogs.com/joemsu/p/7688307.html Spring註解Resource和Autowired區別對比 @Resource和@Autowired都是做bean的注入時使用,其實@Resource並不
從零開始造Spring03---使用構造器注入
前言 上一篇我們實現了setter注入,接下來我們要實現構造器注入。這是學習劉欣老師《從零開始造Spring》課程的學習筆記。 方案說明 類似於setter注入的處理方式,我們還是採用如下三步處理 - 設計一個數據結構 PropertyValue /ConstructorA