Spring框架基礎(chǔ)
1 什么是Spring框架?
Spring框架是框架的框架,因?yàn)槠涮峁┝藢?duì)如Structs,Hibernate憨募,等框架的支持,應(yīng)用Spring框架可以解決不同的技術(shù)上的問(wèn)題(開發(fā)網(wǎng)頁(yè)應(yīng)用袁辈?)菜谣。
Spring框架的優(yōu)勢(shì):
- 預(yù)定義了許多模板。
封裝了JDBC晚缩,Hibernate尾膊,JPA等許多模板。讓我們無(wú)需了解其具體技術(shù)細(xì)節(jié)就可以很輕松的使用它們荞彼。 - 代碼松耦合冈敛。
由依賴注入提供。 - 易于測(cè)試
也是因?yàn)橐蕾囎⑷氲奶匦?/li> - 輕量級(jí)
由于POJO的存在鸣皂,Spring框架不需要程序員繼承任何類或者接口抓谴。 - 快速部署
因?yàn)镾pring框架支持不同的框架,這使得它很容易開發(fā)JavaEE應(yīng)用 - 強(qiáng)大的抽象
對(duì)JavaEE的抽象 - 提供聲明式支持
提供對(duì)緩存寞缝,驗(yàn)證癌压,事務(wù)和格式的聲明式支持。
2 Spring模塊
- Test模塊
提供:使用JUnit和TestNG進(jìn)行測(cè)試 - Core Container
- Core & Beans
提供IOC和依賴注入特性- Context
提供標(biāo)準(zhǔn)國(guó)際化荆陆,EJB滩届,JMS,基礎(chǔ)遠(yuǎn)程 - Expression Language
EL和JSP的擴(kuò)展被啼,提供支持:設(shè)置和獲取屬性值丐吓、方法調(diào)用、訪問(wèn)集合趟据、索引器券犁、訪問(wèn)變量、邏輯和數(shù)學(xué)操作汹碱,通過(guò)對(duì)象名檢索對(duì)象等
- Context
- AOP & Aspects & Instrumentation(檢測(cè))
面向切面編程- Aspects
提供:與AspectJ集成 - Instrumentation
提供:類檢測(cè)粘衬、實(shí)現(xiàn)類加載器
- Aspects
- Data Access / Integration(數(shù)據(jù)訪問(wèn)與集成)
與數(shù)據(jù)庫(kù)交互- JDBC
- ORM
- OXM
- JMS
- Transaction
- Web (MVC / Remoting)
創(chuàng)建Web應(yīng)用- Web
- Web-Servlet
- Web-Struts
- Web-Portlet
- Core & Beans
3 Spring控制反轉(zhuǎn)和依賴注入的一個(gè)小例子
控制反轉(zhuǎn)和依賴注入:消除代碼中的依賴關(guān)系。
Spring使用控制反轉(zhuǎn)和依賴注入來(lái)使程序達(dá)到松耦合的目的咳促。
看一個(gè)小例子:
class Employee{
Address address;
Employee(){
address=new Address();
}
}
這個(gè)例子中稚新,職員類依賴了地址類。創(chuàng)建職員類時(shí)跪腹,先要?jiǎng)?chuàng)建地址類褂删。
class Employee{
Address address;
Employee(Address address){
this.address=address;
}
}
這個(gè)例子中,創(chuàng)建職員類時(shí)冲茸,由外部傳入地址類屯阀,不用再在職員類中創(chuàng)建缅帘,實(shí)現(xiàn)了代碼的松耦合。
4 Spring應(yīng)用的一個(gè)小例子
用你喜歡的ide(或者不用ide)創(chuàng)建Java類Student.java:
package com.javatpoint;
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void displayInfo(){
System.out.println("Hello: "+name);
}
}
創(chuàng)建applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="studentbean" class="com.javatpoint.Student">
<property name="name" value="Vimal Jaiswal"></property>
</bean>
</beans>
創(chuàng)建測(cè)試類Test.java
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);
Student student=(Student)factory.getBean("studentbean");
student.displayInfo();
}
}
導(dǎo)入jar包难衰,jar包下載地址:jar包地址
運(yùn)行Test.java:
- 讀取xml配置文件钦无,存為resource
- 以resource創(chuàng)建一個(gè)beanFactory
- 從beanFactory中獲取在xml中定義好的bean "studentbean"
5 Spring IoC容器
IoC容器的功能:
- 實(shí)例化類
- 配置對(duì)象
- 組裝對(duì)象間的依賴
IoC容器從XML文件獲取信息并根據(jù)信息進(jìn)行工作。
IoC容器類型有兩種:
- BeanFactory
- ApplicationContext
兩種IoC容器的區(qū)別:
ApplicationContext除了具有所有BeanFactory的功能之外盖袭,還提供了額外的功能:
- 集成Spring AOP
- 信息來(lái)源定位
- 事件傳播
- 提供web應(yīng)用的應(yīng)用層具體上下文
5.1 使用IoC容器
使用BeanFactory:
Resource resource =
new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
使用ApplicationContext:
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
6 依賴注入
依賴注入用以移除代碼之間的依賴關(guān)系失暂,降低代碼間的耦合度。
依賴注入的方式有兩種:
- 構(gòu)造器注入
- Setter注入
兩種注入方式的區(qū)別:
- 部分依賴注入只能通過(guò)Setter注入
- Setter注入會(huì)覆蓋構(gòu)造器注入
- Setter注入可以輕松修改bean的值鳄虱,更靈活
6.1 依賴查找(Dependency Lookup)
依賴查找是弟塞,當(dāng)有一個(gè)依賴的需求時(shí),獲取該依賴(資源拙已、對(duì)象)的方式
在不使用依賴注入時(shí)决记,依賴查找的方式(或者說(shuō)new對(duì)象的方式,但后者范圍較小)有:
- new
A obj = new AImpl();
- 工廠方法模式
A obj = A.getA();
- JNDI(Java Naming Directory Interface)
Context ctx = new InitialContext();
Context environmentCtx = (Context) ctx.lookup("java:comp/env");
A obj = (A)environmentCtx.lookup("A");
以上依賴查找的方法的問(wèn)題是:
- 緊耦合
- 不易測(cè)試
使用依賴注入的方式:
class Employee{
Address address;
Employee(Address address){
this.address=address;
}
public void setAddress(Address address){
this.address=address;
}
}
這樣的情況下悠栓,地址類的實(shí)例由構(gòu)造方法或Setter從外部源如XML文件獲得霉涨。
6.1 通過(guò)構(gòu)造器注入基礎(chǔ)類型
Employee.java:
package com.javatpoint;
public class Employee {
private int id;
private String name;
public Employee() {System.out.println("def cons");}
public Employee(int id) {this.id = id;}
public Employee(String name) { this.name = name;}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
void show(){
System.out.println(id+" "+name);
}
}
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="e" class="com.javatpoint.Employee">
<constructor-arg value="10" type="int"></constructor-arg>
</bean>
</beans>
Test.java:
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee s=(Employee)factory.getBean("e");
s.show();
}
}
6.2 通過(guò)構(gòu)造器注入字符串類型
將applicationContext.xml文件主內(nèi)容修改如下:
<bean id="e" class="com.javatpoint.Employee">
<constructor-arg value="10" type="int" ></constructor-arg>
<constructor-arg value="Sonoo"></constructor-arg>
</bean>
6.3 通過(guò)構(gòu)造器注入獨(dú)立對(duì)象
Address.java:
package com.javatpoint;
public class Address {
private String city;
private String state;
private String country;
public Address(String city, String state, String country) {
super();
this.city = city;
this.state = state;
this.country = country;
}
public String toString(){
return city+" "+state+" "+country;
}
}
Address包含三個(gè)屬性按价,一個(gè)構(gòu)造器和一個(gè)toString方法
Employee.java:
package com.javatpoint;
public class Employee {
private int id;
private String name;
private Address address;//Aggregation
public Employee() {System.out.println("def cons");}
public Employee(int id, String name, Address address) {
super();
this.id = id;
this.name = name;
this.address = address;
}
void show(){
System.out.println(id+" "+name);
System.out.println(address.toString());
}
}
Employee包含三個(gè)屬性id惭适,name,address(獨(dú)立對(duì)象)楼镐,兩個(gè)構(gòu)造器和一個(gè)show方法
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="a1" class="com.javatpoint.Address">
<constructor-arg value="ghaziabad"></constructor-arg>
<constructor-arg value="UP"></constructor-arg>
<constructor-arg value="India"></constructor-arg>
</bean>
<bean id="e" class="com.javatpoint.Employee">
<constructor-arg value="12" type="int"></constructor-arg>
<constructor-arg value="Sonoo"></constructor-arg>
<constructor-arg>
<ref bean="a1"/>
</constructor-arg>
</bean>
</beans>
applicationContext.xml配置了兩個(gè)bean:
- Address
通過(guò)Address的構(gòu)造器注入Address的三個(gè)屬性 - Employee
通過(guò)Employee的構(gòu)造器注入Employee的兩個(gè)基礎(chǔ)類型癞志、字符串類型屬性,以及一個(gè)獨(dú)立對(duì)象類型
Test.java
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee s=(Employee)factory.getBean("e");
s.show();
}
}
6.4 通過(guò)構(gòu)造器注入字符串集合
可以注入三種集合類型:
- List
- Set
- Map
Question.java
package com.javatpoint;
import java.util.Iterator;
import java.util.List;
public class Question {
private int id;
private String name;
private List<String> answers;
public Question() {}
public Question(int id, String name, List<String> answers) {
super();
this.id = id;
this.name = name;
this.answers = answers;
}
public void displayInfo(){
System.out.println(id+" "+name);
System.out.println("answers are:");
Iterator<String> itr=answers.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Question具有三個(gè)屬性框产,基礎(chǔ)類型id凄杯,字符串name,以及List集合answers
applicatoinContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="q" class="com.javatpoint.Question">
<constructor-arg value="111"></constructor-arg>
<constructor-arg value="What is java?"></constructor-arg>
<constructor-arg>
<list>
<value>Java is a programming language</value>
<value>Java is a Platform</value>
<value>Java is an Island of Indonasia</value>
</list>
</constructor-arg>
</bean>
</beans>
applicationContext配置了一個(gè)Question的bean:q秉宿,通過(guò)構(gòu)造器注入三個(gè)屬性
Test.java:
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo();
}
}
6.5 通過(guò)構(gòu)造器注入對(duì)象類型集合
Question.java:
package com.javatpoint;
import java.util.Iterator;
import java.util.List;
public class Question {
private int id;
private String name;
private List<Answer> answers;
public Question() {}
public Question(int id, String name, List<Answer> answers) {
super();
this.id = id;
this.name = name;
this.answers = answers;
}
public void displayInfo(){
System.out.println(id+" "+name);
System.out.println("answers are:");
Iterator<Answer> itr=answers.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Question包含三個(gè)屬性戒突,基礎(chǔ)類型id,字符串name描睦,內(nèi)容為Answer對(duì)象的集合
Answer.java:
package com.javatpoint;
public class Answer {
private int id;
private String name;
private String by;
public Answer() {}
public Answer(int id, String name, String by) {
super();
this.id = id;
this.name = name;
this.by = by;
}
public String toString(){
return id+" "+name+" "+by;
}
}
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ans1" class="com.javatpoint.Answer">
<constructor-arg value="1"></constructor-arg>
<constructor-arg value="Java is a programming language"></constructor-arg>
<constructor-arg value="John"></constructor-arg>
</bean>
<bean id="ans2" class="com.javatpoint.Answer">
<constructor-arg value="2"></constructor-arg>
<constructor-arg value="Java is a Platform"></constructor-arg>
<constructor-arg value="Ravi"></constructor-arg>
</bean>
<bean id="q" class="com.javatpoint.Question">
<constructor-arg value="111"></constructor-arg>
<constructor-arg value="What is java?"></constructor-arg>
<constructor-arg>
<list>
<ref bean="ans1"/>
<ref bean="ans2"/>
</list>
</constructor-arg>
</bean>
</beans>
applicationContext定義了兩個(gè)Answer的bean: ans1, ans2, 以及一個(gè)Question的bean:q(利用兩個(gè)ans構(gòu)造)
Test.java:
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo();
}
}
6.6 通過(guò)構(gòu)造器注入字符串類型映射集合
Question.java:
package com.javatpoint;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Question {
private int id;
private String name;
private Map<String,String> answers;
public Question() {}
public Question(int id, String name, Map<String, String> answers) {
super();
this.id = id;
this.name = name;
this.answers = answers;
}
public void displayInfo(){
System.out.println("question id:"+id);
System.out.println("question name:"+name);
System.out.println("Answers....");
Set<Entry<String, String>> set=answers.entrySet();
Iterator<Entry<String, String>> itr=set.iterator();
while(itr.hasNext()){
Entry<String,String> entry=itr.next();
System.out.println("Answer:"+entry.getKey()+" Posted By:"+entry.getValue());
}
}
}
Question包含三個(gè)屬性膊存,id,name忱叭,字符串->字符串映射集合answers
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="q" class="com.javatpoint.Question">
<constructor-arg value="11"></constructor-arg>
<constructor-arg value="What is Java?"></constructor-arg>
<constructor-arg>
<map>
<entry key="Java is a Programming Language" value="Ajay Kumar"></entry>
<entry key="Java is a Platform" value="John Smith"></entry>
<entry key="Java is an Island" value="Raj Kumar"></entry>
</map>
</constructor-arg>
</bean>
</beans>
applicationContext配置了一個(gè)Question的bean:q
Test.java:
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo();
}
}
6.7 通過(guò)構(gòu)造器注入對(duì)象類型映射集合
Question.java:
package com.javatpoint;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Question {
private int id;
private String name;
private Map<Answer,User> answers;
public Question() {}
public Question(int id, String name, Map<Answer, User> answers) {
super();
this.id = id;
this.name = name;
this.answers = answers;
}
public void displayInfo(){
System.out.println("question id:"+id);
System.out.println("question name:"+name);
System.out.println("Answers....");
Set<Entry<Answer, User>> set=answers.entrySet();
Iterator<Entry<Answer, User>> itr=set.iterator();
while(itr.hasNext()){
Entry<Answer, User> entry=itr.next();
Answer ans=entry.getKey();
User user=entry.getValue();
System.out.println("Answer Information:");
System.out.println(ans);
System.out.println("Posted By:");
System.out.println(user);
}
}
}
Question包含三個(gè)屬性隔崎,其中一個(gè)屬性為Answer->User映射類型集合
Answer.java:
package com.javatpoint;
import java.util.Date;
public class Answer {
private int id;
private String answer;
private Date postedDate;
public Answer() {}
public Answer(int id, String answer, Date postedDate) {
super();
this.id = id;
this.answer = answer;
this.postedDate = postedDate;
}
public String toString(){
return "Id:"+id+" Answer:"+answer+" Posted Date:"+postedDate;
}
}
User.java:
package com.javatpoint;
public class User {
private int id;
private String name,email;
public User() {}
public User(int id, String name, String email) {
super();
this.id = id;
this.name = name;
this.email = email;
}
public String toString(){
return "Id:"+id+" Name:"+name+" Email Id:"+email;
}
}
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="answer1" class="com.javatpoint.Answer">
<constructor-arg value="1"></constructor-arg>
<constructor-arg value="Java is a Programming Language"></constructor-arg>
<constructor-arg value="12/12/2001"></constructor-arg>
</bean>
<bean id="answer2" class="com.javatpoint.Answer">
<constructor-arg value="2"></constructor-arg>
<constructor-arg value="Java is a Platform"></constructor-arg>
<constructor-arg value="12/12/2003"></constructor-arg>
</bean>
<bean id="user1" class="com.javatpoint.User">
<constructor-arg value="1"></constructor-arg>
<constructor-arg value="Arun Kumar"></constructor-arg>
<constructor-arg value="arun@gmail.com"></constructor-arg>
</bean>
<bean id="user2" class="com.javatpoint.User">
<constructor-arg value="2"></constructor-arg>
<constructor-arg value="Varun Kumar"></constructor-arg>
<constructor-arg value="Varun@gmail.com"></constructor-arg>
</bean>
<bean id="q" class="com.javatpoint.Question">
<constructor-arg value="1"></constructor-arg>
<constructor-arg value="What is Java?"></constructor-arg>
<constructor-arg>
<map>
<entry key-ref="answer1" value-ref="user1"></entry>
<entry key-ref="answer2" value-ref="user2"></entry>
</map>
</constructor-arg>
</bean>
</beans>
Test.java:
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo();
}
}
6.8 通過(guò)構(gòu)造器注入繼承bean
Employee.java:
package com.javatpoint;
public class Employee {
private int id;
private String name;
private Address address;
public Employee() {}
public Employee(int id, String name) {
super();
this.id = id;
this.name = name;
}
public Employee(int id, String name, Address address) {
super();
this.id = id;
this.name = name;
this.address = address;
}
void show(){
System.out.println(id+" "+name);
System.out.println(address);
}
}
Address.java:
package com.javatpoint;
public class Address {
private String addressLine1,city,state,country;
public Address(String addressLine1, String city, String state, String country) {
super();
this.addressLine1 = addressLine1;
this.city = city;
this.state = state;
this.country = country;
}
public String toString(){
return addressLine1+" "+city+" "+state+" "+country;
}
}
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="e1" class="com.javatpoint.Employee">
<constructor-arg value="101"></constructor-arg>
<constructor-arg value="Sachin"></constructor-arg>
</bean>
<bean id="address1" class="com.javatpoint.Address">
<constructor-arg value="21,Lohianagar"></constructor-arg>
<constructor-arg value="Ghaziabad"></constructor-arg>
<constructor-arg value="UP"></constructor-arg>
<constructor-arg value="USA"></constructor-arg>
</bean>
<bean id="e2" class="com.javatpoint.Employee" parent="e1">
<constructor-arg ref="address1"></constructor-arg>
</bean>
</beans>
employee1使用傳統(tǒng)方式構(gòu)造bean,employee2使用bean繼承方式構(gòu)造bean
Test.java:
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee e1=(Employee)factory.getBean("e2");
e1.show();
}
}
6.9 通過(guò)Setter注入基礎(chǔ)類型韵丑、String類型
Employee.java:
package com.javatpoint;
public class Employee {
private int id;
private String name;
private String city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
void display(){
System.out.println(id+" "+name+" "+city);
}
}
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="obj" class="com.javatpoint.Employee">
<property name="id">
<value>20</value>
</property>
<property name="name">
<value>Arun</value>
</property>
<property name="city">
<value>ghaziabad</value>
</property>
</bean>
</beans>
Test.java:
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee e=(Employee)factory.getBean("obj");
e.display();
}
}
6.10 通過(guò)Setter注入對(duì)象類型
Address.java:
package com.javatpoint;
public class Address {
private String addressLine1, city, state, country;
//getters and setters
public String toString() {
return addressLine1 + " " + city + " " + state + " " + country;
}
}
Employee.java:
package com.javatpoint;
public class Employee {
private int id;
private String name;
private Address address;
//setters and getters
void displayInfo(){
System.out.println(id+" "+name);
System.out.println(address);
}
}
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="address1" class="com.javatpoint.Address">
<property name="addressLine1" value="51,Lohianagar"></property>
<property name="city" value="Ghaziabad"></property>
<property name="state" value="UP"></property>
<property name="country" value="India"></property>
</bean>
<bean id="obj" class="com.javatpoint.Employee">
<property name="id" value="1"></property>
<property name="name" value="Sachin Yadav"></property>
<property name="address" ref="address1"></property>
</bean>
</beans>
Test.java:
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee e=(Employee)factory.getBean("obj");
e.displayInfo();
}
}
6.11 通過(guò)Setter注入集合類型
Questions.java:
package com.javatpoint;
import java.util.Iterator;
import java.util.List;
public class Question {
private int id;
private String name;
private List<String> answers;
//setters and getters
public void displayInfo(){
System.out.println(id+" "+name);
System.out.println("answers are:");
Iterator<String> itr=answers.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="q" class="com.javatpoint.Question">
<property name="id" value="1"></property>
<property name="name" value="What is Java?"></property>
<property name="answers">
<list>
<value>Java is a programming language</value>
<value>Java is a platform</value>
<value>Java is an Island</value>
</list>
</property>
</bean>
</beans>
Test.java:
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo();
}
}
6.12 通過(guò)Setter注入獨(dú)立對(duì)象
Questions.java:
package com.javatpoint;
import java.util.Iterator;
import java.util.List;
public class Question {
private int id;
private String name;
private List<Answer> answers;
//setters and getters
public void displayInfo(){
System.out.println(id+" "+name);
System.out.println("answers are:");
Iterator<Answer> itr=answers.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Answer.java:
<?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="answer1" class="com.javatpoint.Answer">
<property name="id" value="1"></property>
<property name="name" value="Java is a programming language"></property>
<property name="by" value="Ravi Malik"></property>
</bean>
<bean id="answer2" class="com.javatpoint.Answer">
<property name="id" value="2"></property>
<property name="name" value="Java is a platform"></property>
<property name="by" value="Sachin"></property>
</bean>
<bean id="q" class="com.javatpoint.Question">
<property name="id" value="1"></property>
<property name="name" value="What is Java?"></property>
<property name="answers">
<list>
<ref bean="answer1"/>
<ref bean="answer2"/>
</list>
</property>
</bean>
</beans>
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="answer1" class="com.javatpoint.Answer">
<property name="id" value="1"></property>
<property name="name" value="Java is a programming language"></property>
<property name="by" value="Ravi Malik"></property>
</bean>
<bean id="answer2" class="com.javatpoint.Answer">
<property name="id" value="2"></property>
<property name="name" value="Java is a platform"></property>
<property name="by" value="Sachin"></property>
</bean>
<bean id="q" class="com.javatpoint.Question">
<property name="id" value="1"></property>
<property name="name" value="What is Java?"></property>
<property name="answers">
<list>
<ref bean="answer1"/>
<ref bean="answer2"/>
</list>
</property>
</bean>
</beans>
Test.java:
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo();
}
}
6.13 通過(guò)Setter注入非對(duì)象Map
Questions.java:
package com.javatpoint;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Question {
private int id;
private String name;
private Map<String,String> answers;
//getters and setters
public void displayInfo(){
System.out.println("question id:"+id);
System.out.println("question name:"+name);
System.out.println("Answers....");
Set<Entry<String, String>> set=answers.entrySet();
Iterator<Entry<String, String>> itr=set.iterator();
while(itr.hasNext()){
Entry<String,String> entry=itr.next();
System.out.println("Answer:"+entry.getKey()+" Posted By:"+entry.getValue());
}
}
}
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="q" class="com.javatpoint.Question">
<property name="id" value="1"></property>
<property name="name" value="What is Java?"></property>
<property name="answers">
<map>
<entry key="Java is a programming language" value="Sonoo Jaiswal"></entry>
<entry key="Java is a Platform" value="Sachin Yadav"></entry>
</map>
</property>
</bean>
</beans>
Test.java:
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo();
}
}
6.14 通過(guò)Setter注入對(duì)象Map
Questions.java:
package com.javatpoint;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Question {
private int id;
private String name;
private Map<Answer,User> answers;
//getters and setters
public void displayInfo(){
System.out.println("question id:"+id);
System.out.println("question name:"+name);
System.out.println("Answers....");
Set<Entry<Answer, User>> set=answers.entrySet();
Iterator<Entry<Answer, User>> itr=set.iterator();
while(itr.hasNext()){
Entry<Answer, User> entry=itr.next();
Answer ans=entry.getKey();
User user=entry.getValue();
System.out.println("Answer Information:");
System.out.println(ans);
System.out.println("Posted By:");
System.out.println(user);
}
}
}
Answer.java:
package com.javatpoint;
import java.util.Date;
public class Answer {
private int id;
private String answer;
private Date postedDate;
public Answer() {}
public Answer(int id, String answer, Date postedDate) {
super();
this.id = id;
this.answer = answer;
this.postedDate = postedDate;
}
public String toString(){
return "Id:"+id+" Answer:"+answer+" Posted Date:"+postedDate;
}
}
User.java:
package com.javatpoint;
public class User {
private int id;
private String name,email;
public User() {}
public User(int id, String name, String email) {
super();
this.id = id;
this.name = name;
this.email = email;
}
public String toString(){
return "Id:"+id+" Name:"+name+" Email Id:"+email;
}
}
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="answer1" class="com.javatpoint.Answer">
<property name="id" value="1"></property>
<property name="answer" value="Java is a Programming Language"></property>
<property name="postedDate" value="12/12/2001"></property>
</bean>
<bean id="answer2" class="com.javatpoint.Answer">
<property name="id" value="2"></property>
<property name="answer" value="Java is a Platform"></property>
<property name="postedDate" value="12/12/2003"></property>
</bean>
<bean id="user1" class="com.javatpoint.User">
<property name="id" value="1"></property>
<property name="name" value="Arun Kumar"></property>
<property name="email" value="arun@gmail.com"></property>
</bean>
<bean id="user2" class="com.javatpoint.User">
<property name="id" value="2"></property>
<property name="name" value="Varun Kumar"></property>
<property name="email" value="Varun@gmail.com"></property>
</bean>
<bean id="q" class="com.javatpoint.Question">
<property name="id" value="1"></property>
<property name="name" value="What is Java?"></property>
<property name="answers">
<map>
<entry key-ref="answer1" value-ref="user1"></entry>
<entry key-ref="answer2" value-ref="user2"></entry>
</map>
</property>
</bean>
</beans>
Test.java:
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo();
}
}
6.15 通過(guò)Autowire注入
Autowire可以隱式注入依賴:
- 內(nèi)部使用Setter注入
- 內(nèi)部使用構(gòu)造器注入
Autowire:
- 寫更少的代碼
- 不被程序員控制
- 不能作用于基礎(chǔ)類型和字符串
Autowire的模式:
- no
- byName
通過(guò)bean的名字注入bean爵卒,屬性名和bean名必須相同,調(diào)用的是setter注入 - byType
通過(guò)類型注入撵彻,屬性名和bean名可以不同钓株,通過(guò)setter注入 - constructor
通過(guò)調(diào)用構(gòu)造器注入
Autowire的例子如下实牡。
B.java:
package org.sssit;
public class B {
B(){System.out.println("b is created");}
void print(){System.out.println("hello b");}
}
A.java:
package org.sssit;
public class A {
B b;
A(){System.out.println("a is created");}
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
void print(){System.out.println("hello a");}
void display(){
print();
b.print();
}
}
A依賴B。
appliactoin.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="b" class="org.sssit.B"></bean>
<bean id="a" class="org.sssit.A" autowire="byName"></bean>
</beans>
Test.java:
package org.sssit;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
A a=context.getBean("a",A.class);
a.display();
}
}
- 通過(guò)byName方式注入享幽,這種方式必須屬性名與bean名相同:
<bean id="b" class="org.sssit.B"></bean>
<bean id="a" class="org.sssit.A" autowire="byName"></bean>
A中B依賴的屬性名為b铲掐,與bean的id相同
- 通過(guò)byType方式注入,這種方式不必屬性名與bean名相同值桩,但相同類型bean只能有一個(gè):
<bean id="b1" class="org.sssit.B"></bean>
<bean id="a" class="org.sssit.A" autowire="byType"></bean>
此時(shí)只有一個(gè)B類bean摆霉,在a的bean初始化的時(shí)候,當(dāng)發(fā)現(xiàn)缺失b依賴奔坟,會(huì)自動(dòng)到容器中尋找同類型的bean携栋,此時(shí)這種類型的bean只有b1一個(gè),b1被自動(dòng)注入
<bean id="b1" class="org.sssit.B"></bean>
<bean id="b2" class="org.sssit.B"></bean>
<bean id="a" class="org.sssit.A" autowire="byType"></bean>
此時(shí)有兩個(gè)B類bean咳秉,當(dāng)發(fā)現(xiàn)缺失b依賴婉支,會(huì)自動(dòng)到容器中尋找同類型的bean,此時(shí)這種類型的bean只b1澜建、b2兩個(gè)向挖,拋出異常
- 通過(guò)constructor注入:
<bean id="b" class="org.sssit.B"></bean>
<bean id="a" class="org.sssit.A" autowire="constructor"></bean>
如果有多個(gè)參數(shù)的構(gòu)造器,最多參數(shù)的構(gòu)造器將會(huì)被調(diào)用
6.16 通過(guò)工廠方法注入
省略炕舵。
7 Spring AOP
AOP是對(duì)OOP的補(bǔ)充:AOP也提供了模塊化何之。但模塊化的關(guān)鍵點(diǎn)是切面而不是類。
AOP將程序分成獨(dú)立的部分(稱為關(guān)注點(diǎn))咽筋,通過(guò)橫切關(guān)注點(diǎn)(cross-cutting concerns)來(lái)提高模塊化溶推。
橫切關(guān)注點(diǎn)是可以影響整個(gè)程序,應(yīng)該被集中放在一處代碼的關(guān)注點(diǎn)奸攻。如事務(wù)管理蒜危,授權(quán)認(rèn)證,日志記錄睹耐,安全等辐赞。
假設(shè)需要在很多不同的方法中加入相同的關(guān)注點(diǎn),如果不用AOP硝训,編寫和維護(hù)這些方法會(huì)造成很多問(wèn)題响委。
使用AOP,就不需要在這些方法中調(diào)用關(guān)注點(diǎn)的方法捎迫,而將關(guān)注點(diǎn)統(tǒng)一在一個(gè)類中維護(hù)晃酒,通過(guò)XML賦予條目。如果日后這些方法中不需要關(guān)注點(diǎn)窄绒,只需要在XML中修改就可以達(dá)成目的贝次。
7.1 AOP概念和術(shù)語(yǔ)
- Join point:加入點(diǎn)可以是程序中的任意點(diǎn),有方法執(zhí)行彰导,異常處理蛔翅,字段訪問(wèn)等敲茄。Spring只支持方法執(zhí)行加入點(diǎn)。
-
Advice:Advice表示一個(gè)切面在特定join point的操作山析,有以下幾種類型:
- Before Advice:在join point執(zhí)行之前執(zhí)行
- After Retunring Advice:在join point正常結(jié)束才會(huì)執(zhí)行
- After Throwing Advice:如果方法拋出異常才會(huì)執(zhí)行
- After(finally) Advice:不管方法執(zhí)行是否拋出異常堰燎,都會(huì)執(zhí)行的Advice
- Around Advice:在join point之前或之后執(zhí)行
- Pointcut:AOP與加入點(diǎn)相匹配的表達(dá)式語(yǔ)言
- Introduction:
- Target Object:
- Aspect:一個(gè)包含advices,join points的類
- Interceptor:一個(gè)只包含advice的切面
- AOP Proxy:實(shí)現(xiàn)切面合約
- Weaving:連接切面和應(yīng)用程序種類或?qū)ο笏窆欤詣?chuàng)建adviced object
AOP的實(shí)現(xiàn)有:
- AspectJ
- Spring AOP
- Spring 1.2 Old Style(dtd)
- AspectJ annotation-style
- Spring XML configuration-style(schema based)
- JBoss AOP
7.2
Spring 1.2 old style aop advices:
- Aefore Advice
- After Advice
- Around Advice
- Throws Advice
advice層次結(jié)構(gòu)如下:
- advice
- Before Advice
- MethodBeforeAdvice
- After Advice
- AfterRunningAdvice
- ThrowsAdvice
- Inteceptor
- MethodInteceptor
- Before Advice
參考文章: