SSM-Spring
什么是Spring:Spring提供了两个及其重要的技术,IoC |AOP
IoC:控制翻转 也叫DI技术(依赖注入)。之前呢,开发人员在使用某个类之前都需要先去创建对象(new),然后通过setter方法注入值,然后通过这个对象调用其中的方法。。。而现在通过Spring 的 IoC技术可以将对象的创建以及属性的赋值承包起来,这样的话,开发人员无需去创建对象,为属性赋值等。
AOP:面向方面编程(OOP)
1、开发步骤
①、导入jar包
commons-logging-1.1.1.jar
junit4.4.jar
spring-beans-4.0.2.RELEASE.jar
spring-context-4.0.2.RELEASE.jar
spring-core-4.0.2.RELEASE.jar
spring-expression-4.0.2.RELEASE.jar②、创建spring的配置文件
③、配置相关对象
spring-01applicationContext.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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- HelloWorld helloWorld=new HelloWorld(); id:设置对象名 class:设置具体类型,必须是全类名 ,为什么? 因为IoC技术是通过java的refection技术完成的对象实例创建,而反射需要给定全类名 同时注意:HelloWord类中必须提供无参构造 --> <bean id="helloWorld" class="com.rock.spring.hello.HelloWorld"> <property name="name" value="老张"></property> </bean> </beans>
④、去IoC容器中获取这些对象
package com.rock.spring.hello; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class HelloWorldTest { @Test public void test1(){ HelloWorld helloWorld =new HelloWorld(); helloWorld.setName1("老张"); helloWorld.hello(); } public static void main(String[] args) { // HelloWorld helloWorld =new HelloWorld(); // helloWorld.setName("老张"); // ①、创建Spring的IoC容器对象 // ApplicationContext :是IoC容器对象 // ClassPathXmlApplicationContext是ApplicationContext容器对象的一个具体实现,参数指定了spring的配置文件 ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-01applicationContext.xml"); // ②、去IoC容器中获取对象(根据IoC容器中的对象名获取对应的对象) HelloWorld helloWorld=(HelloWorld) ctx.getBean("helloWorld"); // ③、调用对象中的相关方法 helloWorld.hello(); } @Test public void testFirst(){ } }
2、Spring中bean的配置以及属性注入的细节
①、两种属性值注入方式
①、setter方法注入
②、构造器注入,通过bean的构造器先后顺序注入
spring-02beans.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 通过setter方法注入属性值 -->
<!-- 注意:若注入的值中有特殊字符需要使用CDATA方式注入这些含有特殊字符的值 -->
<bean id="c1" class="com.rock.spring.beans.Car">
<property name="brand">
<value><![CDATA[<<BYD>>]]></value>
</property>
<property name="price" value="1000000"></property>
<property name="maxspeed">
<value>240</value>
</property>
</bean>
<bean id="car1" class="com.rock.spring.beans.Car">
<property name="brand" value="Audi"></property>
<property name="price" value="3333333.5"></property>
<property name="maxspeed" value="240"></property>
</bean>
<bean id="car" class="com.rock.spring.beans.Car">
<property name="brand">
<value><![CDATA[a<<ud>>i]]></value>
</property>
<property name="price" value="3333333.5"></property>
<property name="maxspeed" value="240"></property>
</bean>
<bean id="car2" class="com.rock.spring.beans.Car">
<!-- <property name="brand" value="<![CDATA[sss]]>"></property> -->
<!-- <property name="price" value="3333333.5"></property>
<property name="maxspeed" value="240"></property> -->
<!--
通过构造方法注入属性值 ,按照构造方法的参数顺序注入值
constructor-arg元素有两个属性
index属性:值对应的参数索引位置 默认从0开始
type属性:指定构造器参数的类型
-->
<constructor-arg value="BMW" index="0"></constructor-arg>
<constructor-arg value="99999.9"></constructor-arg>
<constructor-arg value="240"></constructor-arg>
</bean>
<bean id="car3" class="com.rock.spring.beans.Car">
<constructor-arg value="Audi"></constructor-arg>
<constructor-arg value="5555555.5"></constructor-arg>
</bean>
<bean id="car4" class="com.rock.spring.beans.Car">
<constructor-arg value="Audi" type="java.lang.String"></constructor-arg>
<constructor-arg value="240" type="double"></constructor-arg>
</bean>
</beans>
②、应用类型属性的注入
spring-03ObjectIn.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
Person peson=new Person();
Car car=new Car();
p.setCar(car);
-->
<bean id="car" class="com.rock.spring.objectin.Car">
<constructor-arg value="Audi"></constructor-arg>
<constructor-arg value="5555555.5"></constructor-arg>
<constructor-arg value="240"></constructor-arg>
</bean>
<bean id="car1" class="com.rock.spring.objectin.Car">
<constructor-arg value="BMW"></constructor-arg>
<constructor-arg value="6555555.5"></constructor-arg>
<constructor-arg value="280"></constructor-arg>
</bean>
<!--
应用类型的属性通过ref注入
前提:这个car对象必须存在于IoC容器中,方可通过ref注入到其他的类中
-->
<bean id="person" class="com.rock.spring.objectin.Person">
<property name="name" value="刘备"></property>
<property name="car" ref="car"></property>
</bean>
<bean id="address" class="com.rock.spring.objectin.Address">
<constructor-arg value="大连"></constructor-arg>
<constructor-arg value="高新区光贤路"></constructor-arg>
</bean>
<bean id="person1" class="com.rock.spring.objectin.Person">
<property name="name">
<value>关羽</value>
</property>
<property name="car" ref="car1"></property>
<property name="address" ref="address"></property>
</bean>
<!-- 通过内部bean注入值 -->
<bean id="person2" class="com.rock.spring.objectin.Person">
<property name="name">
<value>张飞</value>
</property>
<property name="car" ref="car1"></property>
<property name="address">
<!--
通过内部bean向应用类型注入值,内部bean和外部bean的主要区别就是内部bean仅能被当前对象使用,不能被其他的bean应用
这个内部bean无需id属性
-->
<bean class="com.rock.spring.objectin.Address">
<constructor-arg value="北京市"></constructor-arg>
<constructor-arg value="海淀区中软村"></constructor-arg>
</bean>
</property>
</bean>
</beans>
Person.java
package com.rock.spring.objectin;
import java.util.List;
public class Person {
private String name;
private Car car;
private Address address;
private List<Car> cars;
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Person [name=" + name + ", car=" + car + ", address=" + address + ", cars=" + cars + "]";
}
}
ObjectInTest.java
package com.rock.spring.objectin;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ObjectInTest {
ApplicationContext ctx;
@Before
public void init(){
// ①、创建IoC容器对象
ctx=new ClassPathXmlApplicationContext("spring-03ObjectIn.xml");
}
@Test
public void testRef(){
Person person=(Person) ctx.getBean("person");
System.out.println(person);
Person person1=(Person) ctx.getBean("person1");
System.out.println(person1);
Person person2=(Person) ctx.getBean("person2");
System.out.println(person2);
}
}
Car.java
package com.rock.spring.objectin;
public class Car {
private String brand;
private double price;
private int maxspeed;
public Car() {
super();
}
public Car(String brand, double price, int maxspeed) {
super();
this.brand = brand;
this.price = price;
this.maxspeed = maxspeed;
}
public Car(String brand, double price) {
this.brand = brand;
this.price = price;
}
public Car(String brand, int maxspeed) {
this.brand = brand;
this.maxspeed = maxspeed;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + ", maxspeed=" + maxspeed + "]";
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getMaxspeed() {
return maxspeed;
}
public void setMaxspeed(int maxspeed) {
this.maxspeed = maxspeed;
}
}
Address.java
package com.rock.spring.objectin;
public class Address {
private String city;
private String street;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
@Override
public String toString() {
return "Address [city=" + city + ", street=" + street + "]";
}
public Address(String city, String street) {
super();
this.city = city;
this.street = street;
}
public Address() {
super();
}
}
③、集合属性的注入
spring-04collection.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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<bean id="address" class="com.rock.spring.collection.Address">
<constructor-arg value="大连市"></constructor-arg>
<constructor-arg value="沙河口区"></constructor-arg>
</bean>
<bean id="address1" class="com.rock.spring.collection.Address">
<property name="city" value="辽宁省大连市"></property>
<property name="street" value="沙河口区"></property>
</bean>
<!--
通过p命名空间简化属性的注入过程,
语法:命名空间:setter风格的属性="值"
案例:<bean id="" class="" p:city="大连市">
-->
<bean id="address2" class="com.rock.spring.collection.Address" p:city="辽宁省大连市" p:street="沙河口区"></bean>
<!-- spring允许构造器注入和setter方法注入混合使用 -->
<bean id="car" class="com.rock.spring.collection.Car">
<constructor-arg value="BYD"></constructor-arg>
<constructor-arg value="33333.333" type="double"></constructor-arg>
<property name="maxspeed" value="180"></property>
</bean>
<bean id="car1" class="com.rock.spring.collection.Car">
<constructor-arg value="BMW"></constructor-arg>
<constructor-arg value="333333.333" type="double"></constructor-arg>
<property name="maxspeed" value="280"></property>
</bean>
<bean id="car2" class="com.rock.spring.collection.Car">
<constructor-arg value="Audi"></constructor-arg>
<constructor-arg value="433333.333" type="double"></constructor-arg>
<property name="maxspeed" value="300"></property>
</bean>
<!-- 集合属性的注入 -->
<bean id="person" class="com.rock.spring.collection.Person">
<property name="name" value="曹操"></property>
<property name="address" ref="address"></property>
<property name="car" ref="car"></property>
<property name="cars">
<!-- 用于注入List以及Set集合的值 -->
<list>
<ref bean="car"/>
<ref bean="car1"/>
<ref bean="car2"/>
<!-- 也可以直接通过内部bean向List集合中注入值 -->
<bean class="com.rock.spring.collection.Car">
<property name="brand" value="Benz"></property>
</bean>
</list>
</property>
</bean>
<bean id="person1" class="com.rock.spring.collection.Person">
<property name="name" value="曹丕"></property>
<property name="address" ref="address"></property>
<property name="car" ref="car"></property>
<property name="cars1">
<!-- 用于注入List以及Set集合的值 -->
<list>
<ref bean="car"/>
<ref bean="car1"/>
<ref bean="car2"/>
<!-- 也可以直接通过内部bean向List集合中注入值 -->
<bean class="com.rock.spring.collection.Car">
<property name="brand" value="Benz"></property>
</bean>
</list>
</property>
</bean>
<!-- map集合的注入 -->
<bean id="person2" class="com.rock.spring.collection.Person">
<property name="name" value="曹缨"></property>
<property name="address" ref="address2"></property>
<!-- <property name="car" ref="car"></property> -->
<property name="cars2">
<map>
<!--
key属性:指定当前注入的元素的key值
value-ref:指定当前注入的元素的value值
-->
<entry key="C1" value-ref="car"></entry>
<entry key="C2" value-ref="car1"></entry>
<entry key="C3" value-ref="car2"></entry>
</map>
</property>
</bean>
<!-- 使用util命名空间简化配置 ,util定义一个list集合 叫 midCarList-->
<util:list id="midCarList">
<ref bean="car"/>
<ref bean="car1"/>
<ref bean="car2"/>
</util:list>
<bean id="person3" class="com.rock.spring.collection.Person">
<property name="name" value="诸葛亮"></property>
<!-- 通过ref设置外部的util命名空间指定的List集合 -->
<property name="cars" ref="midCarList"></property>
</bean>
<bean id="person4" class="com.rock.spring.collection.Person">
<property name="name" value="诸葛亮"></property>
<property name="cars1" ref="midCarList"></property>
</bean>
</beans>
Address.java
package com.rock.spring.collection;
public class Address {
private String city;
private String street;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
@Override
public String toString() {
return "Address [city=" + city + ", street=" + street + "]";
}
public Address(String city, String street) {
super();
this.city = city;
this.street = street;
}
public Address() {
super();
}
}
Car.java
package com.rock.spring.collection;
public class Car {
private String brand;
private double price;
private int maxspeed;
public Car() {
super();
}
public Car(String brand, double price, int maxspeed) {
super();
this.brand = brand;
this.price = price;
this.maxspeed = maxspeed;
}
public Car(String brand, double price) {
this.brand = brand;
this.price = price;
}
public Car(String brand, int maxspeed) {
this.brand = brand;
this.maxspeed = maxspeed;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + ", maxspeed=" + maxspeed + "]";
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getMaxspeed() {
return maxspeed;
}
public void setMaxspeed(int maxspeed) {
this.maxspeed = maxspeed;
}
}
Person.java
package com.rock.spring.collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Person {
private String name;
private Car car;
private Address address;
private List<Car> cars;
private Set<Car> cars1;
private Map<String,Car> cars2;
public Map<String, Car> getCars2() {
return cars2;
}
public void setCars2(Map<String, Car> cars2) {
this.cars2 = cars2;
}
public Set<Car> getCars1() {
return cars1;
}
public void setCars1(Set<Car> cars1) {
this.cars1 = cars1;
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Person [name=" + name + ", car=" + car + ", address=" + address + ", cars=" + cars + ", cars1=" + cars1
+ ", cars2=" + cars2 + "]";
}
}
TestCollectionIn.java
package com.rock.spring.collection;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestCollectionIn {
ApplicationContext ctx;
@Before
public void init(){
// ①、创建IoC容器对象
ctx=new ClassPathXmlApplicationContext("spring-04collection.xml");
}
@Test
public void testCSFix(){
Car car =(Car) ctx.getBean("car");
System.out.println(car);
}
@Test
public void testPerson(){
Person person =(Person) ctx.getBean("person");
System.out.println(person);
Person person1 =(Person) ctx.getBean("person1");
System.out.println(person1);
Person person2 =(Person) ctx.getBean("person2");
System.out.println(person2);
Person person3 =(Person) ctx.getBean("person3");
System.out.println(person3);
}
}
④、properties注入
DataSrouce.java
package com.rock.spring.properties;
import java.util.Properties;
public class DataSource {
private Properties properties;
public DataSource() {
super();
}
public DataSource(Properties properties) {
super();
this.properties = properties;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
@Override
public String toString() {
return "DataSource [properties=" + properties + "]";
}
}
spring-05properties.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:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<bean id="dataSource" class="com.rock.spring.properties.DataSource">
<property name="properties">
<props>
<prop key="aa">AAAA</prop>
<prop key="bb">BBBB</prop>
<prop key="cc">CCCC</prop>
</props>
</property>
</bean>
<bean id="dataSource1" class="com.rock.spring.properties.DataSource">
<constructor-arg>
<props>
<prop key="driver">oracle.jdbc.OracleDriver</prop>
<prop key="url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</prop>
<prop key="username">scott</prop>
<prop key="password">tiger</prop>
</props>
</constructor-arg>
</bean>
<!-- 导入外部的属性文件
location:classpath:db.properties..classpath 类路径即src下
就可以通过${key}==应用属性文件中的属性值了
-->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource2" class="com.rock.spring.properties.DataSource">
<constructor-arg>
<props>
<prop key="driver">${oracle-driver}</prop>
<prop key="url">${oracle-url}</prop>
<prop key="username">${oracle-username}</prop>
<prop key="password">${oracle-password}</prop>
</props>
</constructor-arg>
</bean>
</beans>
PropertiesTest.java
package com.rock.spring.properties;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class PropertiesTest {
ApplicationContext ctx;
@Before
public void init(){
// ①、创建IoC容器对象
ctx=new ClassPathXmlApplicationContext("spring-05properties.xml");
}
@Test
public void testProperties(){
DataSource ds=(DataSource) ctx.getBean("dataSource");
System.out.println(ds);
DataSource ds1=(DataSource) ctx.getBean("dataSource1");
System.out.println(ds1);
DataSource ds2=(DataSource) ctx.getBean("dataSource2");
System.out.println(ds2);
}
}
⑤、part1总结
Spring框架
1、IoC技术(控制翻转):也叫DI(依赖注入)
IoC容器:ApplicationContext ctx:就是IoC容器对象
ctx.getBean(“对象名”);
2、Aop技术:面向方面(切面)编程
3、关于bean属性值得注入
①、基本类型的注入
②、String类型的注入<bean id="" class=""> <property name="" value=""> </bean>
③、对象属性的注入
<bean id="" class=""> <property name="" ref=""> </bean>
④、集合属性的注入List,Set,Map
<bean id="" class=""> <property name=""> <list> Set&List <ref bean="beanid1"> <ref bean="beanid2"> <list> </property> </bean> <bean id="" class=""> <property name=""> <map> Map <entry key|key-ref|value|value-ref=""> <entry key="A0001" value-ref="person"> <map> </property> </bean>
⑤、Properties属性的注入
<bean id="" class=""> <property name=""> <props> Properties <prop key="K1">KValue1</prop> <prop key="K2">KValue2</prop> <props> </property> </bean>
4、Spring命名空间 context|p|util
context:引用外部的属性文件<context:property-placeholder lication=""> <context:property-placeholder location="classpath:db.properties"/>
在当前的配置文件中通过${key}
<property name="driver" value="${oracle.driver}">
oracle.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl oracle.username=scott oracle.password=tiger oracle.driver=oracle.jdbc.OracleDriver
p:对bean属性的值的注入,即简化了配置
<bean id="" class="" p:name="刘备" p:age="30" p:adddress-ref="addr1"><bean>
util:使用util中的list元素创建共享的集合
<util:list></util:list>
<util:list id="midCarList">
<ref bean="car"/>
<ref bean="car1"/>
<ref bean="car2"/>
</util:list>
<bean id="person3" class="com.rock.spring.collection.Person">
<property name="name" value="诸葛亮"></property>
<!-- 通过ref设置外部的util命名空间指定的List集合 -->
<property name="cars" ref="midCarList"></property>
</bean>
<bean id="person4" class="com.rock.spring.collection.Person">
<property name="name" value="刘备"></property>
<!-- 通过ref设置外部的util命名空间指定的List集合 -->
<property name="cars" ref="midCarList"></property>
</bean>
5、其他
①、内部bean
②、setter风格属性|构造注入
③、setter注入和构造器注入可以混合使用
⑥、SpringBean之间的关系
1、依赖关系:表现的是IoC容器在创建对象的先后顺序
2、继承关系:表现在配置上的继承,而非java中的继承
Address.java
package com.rock.spring.relation;
/**FileName: com.rock.spring.relation Address.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月7日:上午9:28:57
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月7日 老张 1.0 1.0 Version
*
*/
public class Address {
private String city;
private String street;
@Override
public String toString() {
return "Address [city=" + city + ", street=" + street + "]";
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
Car.java
package com.rock.spring.relation;
/**FileName: com.rock.spring.relation Car.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月7日:上午9:13:50
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月7日 老张 1.0 1.0 Version
*
*/
public class Car {
private String brand;
private int maxspeed;
private double price;
@Override
public String toString() {
return "Car [brand=" + brand + ", maxspeed=" + maxspeed + ", price=" + price + "]";
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getMaxspeed() {
return maxspeed;
}
public void setMaxspeed(int maxspeed) {
this.maxspeed = maxspeed;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Car(String brand, int maxspeed) {
super();
this.brand = brand;
this.maxspeed = maxspeed;
}
public Car(String brand, int maxspeed, double price) {
super();
this.brand = brand;
this.maxspeed = maxspeed;
this.price = price;
}
public Car() {
super();
}
}
Person.java
package com.rock.spring.relation;
import java.util.Set;
/**FileName: com.rock.spring.relation Person.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月7日:上午9:13:57
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月7日 老张 1.0 1.0 Version
*
*/
public class Person {
private Car car;
private Address address;
private Set<Car> cars;
public Person(Car car, Address address, Set<Car> cars) {
super();
this.car = car;
this.address = address;
this.cars = cars;
}
public Set<Car> getCars() {
return cars;
}
public void setCars(Set<Car> cars) {
this.cars = cars;
}
public Person(Car car, Address address) {
super();
this.car = car;
this.address = address;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Person(Car car) {
super();
this.car = car;
}
public Person() {
super();
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
@Override
public String toString() {
return "Person [car=" + car + ", address=" + address + ", cars=" + cars + "]";
}
}
DepentTest.java
package com.rock.spring.relation;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**FileName: com.rock.spring.relation DependTest.java
* TODO: Bean之间的关系单元测试
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月7日:上午9:20:58
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月7日 老张 1.0 1.0 Version
*
*/
public class DependTest {
private ApplicationContext ctx;
@Before
public void init(){
ctx=new ClassPathXmlApplicationContext("spring-06relation.xml");
}
@Test
public void testDep(){
Person person=(Person) ctx.getBean("person");
System.out.println(person);
Person person1=(Person) ctx.getBean("person1");
System.out.println(person1);
}
}
spring-06relation.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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!--
bean之间的关系:
①、依赖关系
spring的bean之间的依赖关系主要体现在IoCo容器创建bean对象的先后顺序上,通过depends-on属性设置依赖关系
depends-on="car" IoC容器会先去创建car这个对象
注意:若某个bean依赖多个其他对象,在depends-on属性上可以通过,号分割
-->
<bean id="person" class="com.rock.spring.relation.Person" p:address-ref="address" depends-on="car,address">
<property name="car" ref="car"></property>
</bean>
<bean id="car" class="com.rock.spring.relation.Car">
<constructor-arg value="Audi"></constructor-arg>
<constructor-arg value="260"></constructor-arg>
</bean>
<bean id="address" class="com.rock.spring.relation.Address" p:city="辽宁大连" p:street="高新园区"></bean>
<!-- ②、继承关系 这里说的继承和java中的extends不是类的继承,而是配置的继承
Java : 父类 子类
Spring: 父Bean 子Bean
因为Spring中的继承是指配置上的继承关系,
而不是为了创建对象纳入IoC容器管理,所以一般来说,父bean都设置为抽象bean。,通过abstract="true"设置bean为抽象的
子bean:通过parent属性设置其父Bean对象
-->
<bean id="fatherCar" abstract="true" p:brand="Audi" p:maxspeed="260" p:price="300000"></bean>
<bean id="car1" class="com.rock.spring.relation.Car" p:price="200000" parent="fatherCar" p:brand="Foud"></bean>
<bean id="car2" class="com.rock.spring.relation.Car" parent="fatherCar" p:price="400000"></bean>
<util:set id="utilCars">
<ref bean="car1"/>
<ref bean="car2"/>
</util:set>
<bean id="person1" class="com.rock.spring.relation.Person">
<property name="address" ref="address"></property>
<property name="cars" ref="utilCars"></property>
</bean>
</beans>
⑦、Bean的作用域,IoCbean的作用域共有5个
Spring中bean的作用域
①、singleton :单例作用域,,,
sigleton在项目 启动时,IoC容器就会根据配置创建这个bean对象。是bean的默认作用域
②、prototype :原生作用域,,, prototpye是在获取这个对象时,IoC容器才去创建这个bean对象
③、request
④、session
④、global
Car.java
package com.rock.spring.scope;
/**FileName: com.rock.spring.relation Car.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月7日:上午9:13:50
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月7日 老张 1.0 1.0 Version
*
*/
public class Car {
private String brand;
private int maxspeed;
private double price;
@Override
public String toString() {
return "Car [brand=" + brand + ", maxspeed=" + maxspeed + ", price=" + price + "]";
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getMaxspeed() {
return maxspeed;
}
public void setMaxspeed(int maxspeed) {
this.maxspeed = maxspeed;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Car(String brand, int maxspeed) {
super();
this.brand = brand;
this.maxspeed = maxspeed;
}
public Car(String brand, int maxspeed, double price) {
super();
this.brand = brand;
this.maxspeed = maxspeed;
this.price = price;
}
public Car() {
super();
System.out.println("Car.Car() is running.........");
}
}
Person.java
package com.rock.spring.scope;
import java.util.Set;
/**FileName: com.rock.spring.relation Person.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月7日:上午9:13:57
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月7日 老张 1.0 1.0 Version
*
*/
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
ScopeTest.java
package com.rock.spring.scope;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**FileName: com.rock.spring.relation DependTest.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月7日:上午9:20:58
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月7日 老张 1.0 1.0 Version
*
*/
public class ScopeTest {
private ApplicationContext ctx;
@Before
public void init(){
ctx=new ClassPathXmlApplicationContext("spring-07beanscope.xml");
}
@Test
public void testScope(){
Car car1=(Car) ctx.getBean("car");
Car car2=(Car) ctx.getBean("car");
System.out.println(car1==car2);
// System.out.println(car);
Person p1=(Person) ctx.getBean("person");
Person p2=(Person) ctx.getBean("person");
System.out.println(p1==p2);
}
}
spring-07beanscope.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.xsd">
<!--
通过bean元素的scope属性可以设置bean的作用域,其中有五个取值,即五个作用域,singleton|prototype|request|session|global
区别:
①、bean创建的时机不同,singleton是在IoC容器对象被创建时,IoC会自动创建bean对象,而prototype在从IoC容器中获取这个这个对象时才被IoC创建
②、singleton作用域的多个对象是相等的,而prototype是不相等的。
-->
<bean id="car" class="com.rock.spring.scope.Car" p:brand="Audi" p:maxspeed="240" p:price="300000" scope="singleton"></bean>
<bean id="person" class="com.rock.spring.scope.Person" p:name="刘备" p:age="20" scope="prototype"></bean>
</beans>
⑧、Bean的声明周期
Spring中bean的生命周期:
①、在bean的配置中可以通过init-method 和 destroy -method 来指定bean初始化方法和消亡方法
<bean id="car1" class="com.rock.spring.cycle.Car" p:brand="Audi" p:price="300000" p:maxspeed="240" init-method="init1" destroy-method="destroy1" > </bean>
②、开发人员可以通过创建BeanPostProcessor来设置bean的前置和后置处理器,来进一步干预bean的生命周期
注意:Bean的处理器不是针对某一个bean而是对IoC容器中的所有bean都起作用
Car.java
package com.rock.spring.cycle;
/**FileName: com.rock.spring.relation Car.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月7日:上午9:13:50
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月7日 老张 1.0 1.0 Version
*
*/
public class Car {
private String brand;
private int maxspeed;
private double price;
/**
* @TODO :在这个类被IoC容器创建时 自动调用init方法,完成一些初始化工作
* @Date :2018年11月7日 下午1:20:33
* @Author :老张 :
*/
public void init1(){
System.out.println("Car.init() is running..........");
}
/**
* @TODO :在这个类对象被IoC容器消亡时,会自动调用的方法
* @Date :2018年11月7日 下午1:21:05
* @Author :老张 :
*/
public void destroy1(){
System.out.println("Car.destroy() is running.......");
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getMaxspeed() {
return maxspeed;
}
public void setMaxspeed(int maxspeed) {
this.maxspeed = maxspeed;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Car(String brand, int maxspeed) {
super();
this.brand = brand;
this.maxspeed = maxspeed;
}
public Car(String brand, int maxspeed, double price) {
super();
this.brand = brand;
this.maxspeed = maxspeed;
this.price = price;
}
public Car() {
super();
System.out.println("Car.Car() is running.........");
}
@Override
public String toString() {
return "Car [brand=" + brand + ", maxspeed=" + maxspeed + ", price=" + price + "]";
}
}
Person.java
package com.rock.spring.cycle;
public class Person {
private String name;
private Car car;
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [name=" + name + ", car=" + car + "]";
}
}
CycleTest.java
package com.rock.spring.cycle;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**FileName: com.rock.spring.cycle RockProcessor.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月7日:下午1:35:17
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月7日 老张 1.0 1.0 Version
*/
public class RockProcessor implements BeanPostProcessor{
/**
* 配置bean的后置处理器,
* arg0是IoC容器创建的对象,而返回值IoC容器得到的对象
*/
public Object postProcessAfterInitialization(Object arg0, String arg1) throws BeansException {
// System.out.println("RockProcessor.postProcessAfterInitialization() is running.......");
System.out.println(arg0);
System.out.println(arg1);
Car car=(Car)arg0;
if(car.getBrand().equals("BYD")){
car.setBrand("Audi");
return car;
}
return null;
}
@Override
public Object postProcessBeforeInitialization(Object arg0, String arg1) throws BeansException {
// System.out.println("RockProcessor.postProcessBeforeInitialization() is running.........");
return arg0;
}
}
spring-08beancycle.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.xsd">
<bean id="car1" class="com.rock.spring.cycle.Car"
p:brand="BYD"
p:price="30000"
p:maxspeed="240"
></bean>
<!--
init-method="init1"
destroy-method="destroy1"
-->
<!-- <bean id="car2" class="com.rock.spring.cycle.Car" p:brand="BMW" p:price="350000" p:maxspeed="260"></bean> -->
<bean class="com.rock.spring.cycle.RockProcessor"></bean>
<!-- <bean id="person" class="com.rock.spring.cycle.Person" p:name="张飞" p:car-ref="car1"></bean> -->
</beans>
⑨、自动注入,autowire
<?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.xsd">
<bean id="car11111111" class="com.rock.spring.autowired.Car" p:brand="Audi" p:maxspeed="240" p:price="300000"></bean>
<bean id="address" class="com.rock.spring.autowired.Address" p:city="大连市" p:street="高新园区"></bean>
<bean id="person" class="com.rock.spring.autowired.Person">
<property name="name" value="刘备"></property>
<!-- <property name="car" ref="car"></property> -->
<property name="address" ref="address"></property>
</bean>
<!-- 自动注入,织入 -->
<!-- <bean id="person1" class="com.rock.spring.autowired.Person" autowire="byName">
<property name="name" value="关羽"></property>
byName:根据IoC容器中的对象名(id属性值)和当前对象中的属性名是否一致。进行自动注入
byType:根据IoC容器中的对象的类型和当前bean中的属性类型是否一致,进行自动注入(当前IoC容器中只有一个同属性类型的对象存在)
</bean> -->
<bean id="person2" class="com.rock.spring.autowired.Person" autowire="byType">
<property name="name" value="张飞"></property>
</bean>
</beans>
package com.rock.spring.autowired;
public class Person {
private String name;
private Car car;
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Person [name=" + name + ", car=" + car + ", address=" + address + "]";
}
}
|Spring中属性的注入?
①、setter注入
②、构造器注入
③、自动注入 autowire=“byName|byType” byType:若IoC容器中存在多个相同类型的对象,将不能注入成功
Spring IoC容器管理bean的生命周期
①、通过指定init-method destroy-method 执行初始化和消亡方法
②、bean的后置处理BeanProcessor(接口—>before|after)在bean初始化方法执行之前和执行之后调用before和after方法
注意:两个方法参数以及返回值的性质
参数1:bean对象(Object)
参数2:bean名称(String)
返回值:Object 返回给IoC的对象
③、Bean的创建
Ⅰ、通过静态(工厂)方法创建bean
Ⅱ、通过实例工厂方法创建bean
Ⅲ、通过FactoryBean创建bean
Spring中的表达式语言:SpEL
语法:#{}
⑩、Bean的创建方式
①、通过反射创建bean
②、通过工厂方法创建bean
1)、静态工方法创建bean
第一:工厂中的方法必须是static修饰,返回值是要创建的bean对象类型
第二:这个静态工厂方法可以有参数,若有参数在配置文件中通过向这个参数注入相关的值
第三:在配置文件中配置的Bean类型,但是class要指向工厂类 2)、实例工厂方法创建
③、通过FactoryBean创建
1、工厂方法创建bean
①、静态工厂方法创建bean
PersonFactory.java
package com.rock.spring.beancreate;
import java.util.HashMap;
import java.util.Map;
/**FileName: com.rock.spring.beancreate PersonFactory.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月7日:下午5:05:06
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月7日 老张 1.0 1.0 Version
*
*/
public class PersonFactory {
private static Map<String,Person> ps=new HashMap<String,Person>();
static{
ps.put("zhangfei", new Person("张飞",20));
ps.put("guanyu", new Person("关羽",30));
ps.put("liubei", new Person("刘备",60));
ps.put("zhaoyun", new Person("赵云",10));
}
public static Person getPerson(){
Person p=new Person();
p.setAge(10);
p.setName("张飞");
return p;
}
public static Person getPersonByName(String name){
return ps.get(name);
}
}
AddressFactory
package com.rock.spring.beancreate;
import java.util.HashMap;
import java.util.Map;
/**FileName: com.rock.spring.beancreate AddressFactory.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月7日:下午5:15:28
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月7日 老张 1.0 1.0 Version
*
*/
public class AddressFactory {
private Map<String,Address> maps=new HashMap<>();
{
maps.put("rock", new Address("大连市","高新园区"));
maps.put("zhaoyun", new Address("北京市","海淀区"));
maps.put("liubei", new Address("上海市","黄埔区"));
}
public Address getAddress(String id){
return maps.get(id);
}
}
spring-10beanfactory.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.xsd">
<bean id="car" class="com.rock.spring.beancreate.CarFactory" factory-method="getCar"></bean>
<bean id="car1" class="com.rock.spring.beancreate.CarFactory" factory-method="getCarByCid">
<constructor-arg value="c2"></constructor-arg>
</bean>
<bean id="person" class="com.rock.spring.beancreate.PersonFactory" factory-method="getPerson"></bean>
<bean id="person1" class="com.rock.spring.beancreate.PersonFactory" factory-method="getPersonByName">
<constructor-arg value="关羽"></constructor-arg>
</bean>
<!-- 通过静态工厂方法创建bean
由于静态方法在调用时无需创建对象,所以静态工厂方法创建bean直接通过factory-method属性指向静态方法名即可
-->
<bean id="person2" class="com.rock.spring.beancreate.PersonFactory" factory-method="getPersonByName">
<constructor-arg value="zhaoyun"></constructor-arg>
</bean>
<!-- 通过实例工厂方法创建bean -->
<!--
由于采用了实例工厂方法创建bean,所以在调用这个实例方法之前必须先把工厂bean创建出来
factory-bean=实例工厂的bean对象
factory-method=实例工厂类中的实例方法
-->
<bean id="af" class="com.rock.spring.beancreate.AddressFactory"></bean>
<bean id="address1" class="com.rock.spring.beancreate.AddressFactory" factory-bean="af" factory-method="getAddress">
<constructor-arg value="liubei"></constructor-arg>
</bean>
</beans>
FactoryTest
package com.rock.spring.beancreate;
import javax.swing.plaf.synth.SynthSliderUI;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class FactoryTest {
ApplicationContext ctx;
@Before
public void init(){
// ①、创建IoC容器对象
ctx=new ClassPathXmlApplicationContext("spring-10beanfactory.xml");
}
@Test
public void testFactory1(){
Car car=(Car) ctx.getBean("car");
System.out.println(car);
}
@Test
public void testFactory(){
Car car=(Car) ctx.getBean("car1");
System.out.println(car);
}
@Test
public void testPerson(){
Person person=(Person)ctx.getBean("person");
System.out.println(person);
Person person1=(Person)ctx.getBean("person1");
System.out.println(person1);
Person person2=(Person)ctx.getBean("person2");
System.out.println(person2);
}
@Test
public void testAddress(){
Address address1=(Address) ctx.getBean("address1");
System.out.println(address1);
}
}
②、实例工厂方法
Book.java
package com.rock.spring.beancreate;
/**FileName: com.rock.spring.beancreate Book.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月8日:上午8:57:21
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月8日 老张 1.0 1.0 Version
*
*/
public class Book {
private String bookname;
private int price;
public String getBookname() {
return bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "Book [bookname=" + bookname + ", price=" + price + "]";
}
}
BookFactory
package com.rock.spring.beancreate;
/**FileName: com.rock.spring.beancreate BookFactory.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月8日:上午8:58:02
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月8日 老张 1.0 1.0 Version
*
*/
public class BookFactory {
public static Book getBook(){
Book book =new Book();
book.setBookname("老张教程");
book.setPrice(1);
return book;
}
public static Book getBook(String name){
Book book =new Book();
book.setBookname(name);
book.setPrice(1111);
return book;
}
public Book getBook1(){
Book book =new Book();
book.setBookname("老张教程111111");
book.setPrice(11111);
return book;
}
public Book getBook1(String name){
Book book =new Book();
book.setBookname(name);
book.setPrice(2222);
return book;
}
}
BookTest.java
package com.rock.spring.beancreate;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**FileName: com.rock.spring.beancreate BookTest.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月8日:上午9:02:19
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月8日 老张 1.0 1.0 Version
*
*/
public class BookTest {
ApplicationContext ctx;
@Before
public void init(){
// ①、创建IoC容器对象
ctx=new ClassPathXmlApplicationContext("spring-10beanfactory.xml");
}
@Test
public void testBook(){
System.out.println(ctx.getBean("book1"));
System.out.println(ctx.getBean("book2"));
System.out.println(ctx.getBean("book3"));
System.out.println(ctx.getBean("book4"));
}
}
spring-10beanfactory.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.xsd">
<bean id="car" class="com.rock.spring.beancreate.CarFactory" factory-method="getCar"></bean>
<bean id="car1" class="com.rock.spring.beancreate.CarFactory" factory-method="getCarByCid">
<constructor-arg value="c2"></constructor-arg>
</bean>
<bean id="person" class="com.rock.spring.beancreate.PersonFactory" factory-method="getPerson"></bean>
<bean id="person1" class="com.rock.spring.beancreate.PersonFactory" factory-method="getPersonByName">
<constructor-arg value="关羽"></constructor-arg>
</bean>
<!-- 通过静态工厂方法创建bean
由于静态方法在调用时无需创建对象,所以静态工厂方法创建bean直接通过factory-method属性指向静态方法名即可
-->
<bean id="person2" class="com.rock.spring.beancreate.PersonFactory" factory-method="getPersonByName">
<constructor-arg value="zhaoyun"></constructor-arg>
</bean>
<!-- 通过实例工厂方法创建bean -->
<!--
由于采用了实例工厂方法创建bean,所以在调用这个实例方法之前必须先把工厂bean创建出来
factory-bean=实例工厂的bean对象
factory-method=实例工厂类中的实例方法
-->
<bean id="af" class="com.rock.spring.beancreate.AddressFactory"></bean>
<bean id="address1" class="com.rock.spring.beancreate.AddressFactory" factory-bean="af" factory-method="getAddress">
<constructor-arg value="liubei"></constructor-arg>
</bean>
<bean id="book" class="com.rock.spring.beancreate.Book" p:bookname="abc" p:price="22"></bean>
<bean id="book1" class="com.rock.spring.beancreate.BookFactory" factory-method="getBook"></bean>
<bean id="book2" class="com.rock.spring.beancreate.BookFactory" factory-method="getBook">
<constructor-arg value="三国演义"></constructor-arg>
</bean>
<bean id="bookF" class="com.rock.spring.beancreate.BookFactory"></bean>
<bean id="book3" factory-bean="bookF" factory-method="getBook1"></bean>
<bean id="book4" factory-bean="bookF" factory-method="getBook1">
<constructor-arg value="水浒传"></constructor-arg>
</bean>
</beans>
2、FactoryBean创建bean
Car.java
package com.rock.spring.factorybean;
/**FileName: com.rock.spring.factorybean Car.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月8日:上午9:11:27
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月8日 老张 1.0 1.0 Version
*
*/
public class Car {
private String brand;
private double price;
private int maxspeed;
public Car() {
super();
}
public Car(String brand, double price, int maxspeed) {
super();
this.brand = brand;
this.price = price;
this.maxspeed = maxspeed;
}
public Car(String brand, double price) {
this.brand = brand;
this.price = price;
}
public Car(String brand, int maxspeed) {
this.brand = brand;
this.maxspeed = maxspeed;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + ", maxspeed=" + maxspeed + "]";
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getMaxspeed() {
return maxspeed;
}
public void setMaxspeed(int maxspeed) {
this.maxspeed = maxspeed;
}
}
CarFactory.java
package com.rock.spring.factorybean;
import org.springframework.beans.factory.FactoryBean;
/**FileName: com.rock.spring.factorybean CarFactory.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月8日:上午9:11:57
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月8日 老张 1.0 1.0 Version
*
*/
public class CarFactory implements FactoryBean<Car> {
@Override
public Car getObject() throws Exception {
return new Car("Audi",300000);
}
@Override
public Class<?> getObjectType() {
return Car.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
spring-11factorybean.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<bean id="car" class="com.rock.spring.factorybean.CarFactory"></bean>
<bean id="person" class="com.rock.spring.factorybean.PersonFactory"></bean>
</beans>
⑪、spEL表达式为属性注入动态的值
A.java
package com.rock.spring.spel;
public class A {
public static int a=10;
}
Car.java
package com.rock.spring.spel;
/**FileName: com.rock.spring.spel Car.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月8日:上午10:28:20
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月8日 老张 1.0 1.0 Version
*
*/
public class Car {
private String brand;
private double price;
private int maxspeed;
private String info;
/**
* @return the info
*/
public String getInfo() {
return info;
}
/**
* @param info the info to set
*/
public void setInfo(String info) {
this.info = info;
}
/**
* @return the brand
*/
public String getBrand() {
return brand;
}
/**
* @param brand the brand to set
*/
public void setBrand(String brand) {
this.brand = brand;
}
/**
* @return the price
*/
public double getPrice() {
return price;
}
/**
* @param price the price to set
*/
public void setPrice(double price) {
this.price = price;
}
/**
* @return the maxspeed
*/
public int getMaxspeed() {
return maxspeed;
}
/**
* @param maxspeed the maxspeed to set
*/
public void setMaxspeed(int maxspeed) {
this.maxspeed = maxspeed;
}
/**
* @Author :Rock
* @Date :2017年7月31日 下午1:10:32
* @TODO :
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + ", maxspeed="
+ maxspeed + ", info=" + info + "]";
}
}
Person.java
package com.rock.spring.spel;
/**FileName: com.rock.spring.spel Person.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月8日:上午10:28:33
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月8日 老张 1.0 1.0 Version
*
*/
public class Person {
private String name;
private int age;
private Car car;
private int degree;
private boolean type;
/**
* @Author :Rock
* @Date :2017锟斤拷7锟斤拷31锟斤拷 锟斤拷锟斤拷1:29:55
* @TODO :
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", car=" + car
+ ", degree=" + degree + ", type=" + type + "]";
}
/**
* @return the type
*/
public boolean getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(boolean type) {
this.type = type;
}
/**
* @return the degree
*/
public int getDegree() {
return degree;
}
/**
* @param degree the degree to set
*/
public void setDegree(int degree) {
this.degree = degree;
}
/**
*
*/
public Person() {
super();
}
/**
* @param name
* @param age
* @param car
*/
public Person(String name, int age, Car car) {
this.name = name;
this.age = age;
this.car = car;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the car
*/
public Car getCar() {
return car;
}
/**
* @param car the car to set
*/
public void setCar(Car car) {
this.car = car;
}
}
Address.java
package com.rock.spring.spel;
/**FileName: com.rock.spring.spel Address.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月8日:上午10:28:09
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月8日 老张 1.0 1.0 Version
*
*/
public class Address {
private String province;
private String city;
private String addressInfo;
/**
* @return the addressInfo
*/
public String getAddressInfo() {
return addressInfo;
}
/**
* @param addressInfo the addressInfo to set
*/
public void setAddressInfo(String addressInfo) {
this.addressInfo = addressInfo;
}
/**
* @return the province
*/
public String getProvince() {
return province;
}
/**
* @param province the province to set
*/
public void setProvince(String province) {
this.province = province;
}
/**
* @return the city
*/
public String getCity() {
return city;
}
/**
* @param city the city to set
*/
public void setCity(String city) {
this.city = city;
}
/**
* @Author :Rock
* @Date :2017年7月31日 下午1:25:36
* @TODO :
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Address [province=" + province + ", city=" + city
+ ", addressInfo=" + addressInfo + "]";
}
}
SpELTest.java
package com.rock.spring.spel;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**FileName: com.rock.spring.spel SpelTest.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: 老张
* @Date: 2018年11月8日:上午10:28:41
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2018年11月8日 老张 1.0 1.0 Version
*
*/
public class SpelTest {
ApplicationContext ctx;
@Before
public void init(){
ctx=new ClassPathXmlApplicationContext("spring-spel.xml");
}
@Test
public void testValue() {
Car car=(Car) ctx.getBean("car");
System.out.println(car);
}
@Test
public void testObejctValue() {
Person person=(Person) ctx.getBean("person");
System.out.println(person);
}
@Test
public void testObejctPropertyValue() {
Car car=(Car) ctx.getBean("car1");
System.out.println(car);
}
@Test
public void testStringAdd() {
Address address=(Address) ctx.getBean("address1");
System.out.println(address);
}
@Test
public void testStringGe() {
Person person2=(Person) ctx.getBean("person2");
System.out.println(person2);
}
@Test
public void testRelation() {
Person person1=(Person) ctx.getBean("person1");
Person person2=(Person) ctx.getBean("person2");
Person person3=(Person) ctx.getBean("person3");
System.out.println(person1);
System.out.println(person2);
System.out.println(person3);
}
@Test
public void testStaticFinal() {
Car car=(Car) ctx.getBean("car3");
System.out.println(car);
}
@Test
public void testCondition() {
Car car=(Car) ctx.getBean("car5");
System.out.println(car);
}
@Test
public void testCondition1() {
Car car=(Car) ctx.getBean("car3");
System.out.println(car);
}
}
spring-13spel.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.xsd">
<!--
spEL:可以动态的为bean中的属性注入值
①、注入字面值 (可以是对象)
②、可以在sqPL中使用运算符将运算的结果注入到bean中
③、访问类中的静态属性 #{T(全类名).类变量名}
④、在spEL中使用.访问IoC容器中对象的属性 #{person.age}
-->
<!-- ①、字面值注入 -->
<bean id="car" class="com.rock.spring.beans.spel.Car">
<property name="brand" value="#{'Audi'}"></property>
<property name="price" value="#{300000}"></property>
<property name="maxspeed" value="240"></property>
</bean>
<!-- ①、在value属性中通过spEL注入引用类型值 -->
<bean id="person" class="com.rock.spring.beans.spel.Person">
<property name="name" value="刘备"></property>
<property name="car" value="#{car}"></property>
<!-- <property name="car" ref="car"></property> -->
</bean>
<!-- ①、在value属性中通过spEL调用其他bean对象中的属性 -->
<bean id="car1" class="com.rock.spring.beans.spel.Car">
<property name="brand" value="#{'BYD'}"></property>
<!-- car.price:访问了IoC容器中的car对象内的price值 -->
<property name="price" value="#{car.price-100000}"></property>
<property name="maxspeed" value="#{car.maxspeed%7}"></property>
</bean>
<!-- ②、在spEL中使用运算符 -->
<bean id="address" class="com.rock.spring.beans.spel.Address" p:province="辽宁省" p:city="大连市"></bean>
<bean id="address1" class="com.rock.spring.beans.spel.Address" p:addressInfo="#{address.province+address.city}"></bean>
<!-- ApplicationContext cxt=new ClassPathXMlApplicationContext("spring-spel.xml"); -->
<bean id="person1" class="com.rock.spring.beans.spel.Person">
<property name="name" value="关羽"></property>
<property name="degree" value="2"></property>
</bean>
<!-- ②、在spEL中使用运算符 -->
<bean id="person2" class="com.rock.spring.beans.spel.Person">
<property name="name" value="关羽"></property>
<!-- <property name="type" value="#{person1.degree lt 2}"></property> -->
<property name="type" value="#{person1.degree ge 2 }"></property>
</bean>
<!-- ②、在spEL中使用运算符 -->
<bean id="person3" class="com.rock.spring.beans.spel.Person">
<property name="name" value="关羽"></property>
<!-- <property name="type" value="#{person1.degree lt 2}"></property> -->
<property name="type" value="#{not(person1.degree ge 1) }"></property>
</bean>
<bean id="car2" class="com.rock.spring.beans.spel.Car">
<property name="brand" value="#{'BMW'}"></property>
<property name="price" value="#{300000}"></property>
<property name="maxspeed" value="240"></property>
</bean>
<!-- ③、访问类中的静态属性 #{T(全类名).类变量名} -->
<bean id="car3" class="com.rock.spring.beans.spel.Car">
<property name="info" value="#{T(com.rock.spring.beans.spel.A).a-3}"></property>
</bean>
<bean id="car4" class="com.rock.spring.beans.spel.Car">
<property name="brand" value="#{'BMW'}"></property>
<property name="price" value="#{300000}"></property>
<property name="maxspeed" value="240"></property>
</bean>
<!-- ④、在spEL中使用.访问IoC容器中对象的属性 #{person.age} -->
<bean id="car5" class="com.rock.spring.beans.spel.Car">
<property name="info" value="#{car4.price>200000?'土豪':'正常人'}"></property>
</bean>
</beans>
⑫、Spring注解(annotation)
spring-12annotation.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!--
定义有Spring自动扫描一个包,若包下通过了注解定义了相关对象,spring会自动将其纳入到IoC容器中进行管理
可以指定* :所有的注解都被解析
-->
<context:component-scan base-package="com.rock.spring.beans.annotation"></context:component-scan>
<!-- 导入外部的属性文件 -->
<context:property-placeholder location="classpath:db.properties"/>
</beans>
AnnotationTest.java
package com.rock.spring.beans.annotation;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AnnotationTest {
private ApplicationContext ctx;
@Before
public void init(){
ctx=new ClassPathXmlApplicationContext("spring-12annotation.xml");
}
@Test
public void testComponent() {
Car car=(Car) ctx.getBean("car");
System.out.println(car);
}
@Test
public void testComponentNewCar() {
NewCar car=(NewCar) ctx.getBean("okCar");
System.out.println(car);
}
@Test
public void testPropertiesOutFile() {
DataSource dataSource=(DataSource) ctx.getBean("dataSource");
System.out.println(dataSource);
}
@Test
public void testController() {
UserAction userAction=(UserAction) ctx.getBean("userAction");
System.out.println(userAction);
userAction.doGet();
}
}
Car.java
package com.rock.spring.beans.annotation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
/**
*
* FileName: com.rock.spring.beans.annotation Car.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: Rock
* @Date: 2017年7月31日:下午4:18:36
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2017年7月31日 Rock 1.0 1.0 Version
*
*/
//@Component等价与<bean id="car" class="com.rock.spring.beans.annotation.Car">
//springIoc中对象的默认命名规则 Car->car UserAction->userAction
@Component
@Scope(value="prototype")
public class Car {
@Value(value="Audi")
private String brand;
@Value(value="#{T(java.lang.Math).PI*10}")
private double price;
/**
*
*/
public Car() {
System.out.println("Car.Car() is running......");
}
/**
* @Author :Rock
* @Date :2017年7月31日 下午4:19:14
* @TODO :
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Car [brand=" + brand + ", price=" + price + "]";
}
}
User.java
package com.rock.spring.beans.annotation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
*
* FileName: com.rock.spring.beans.annotation User.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: Rock
* @Date: 2017年7月31日:下午4:50:53
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2017年7月31日 Rock 1.0 1.0 Version
*
*/
@Component
public class User {
@Value("Ruby")
private String userid;
@Value("刘备")
private String username;
/**
* @return the userid
*/
public String getUserid() {
return userid;
}
/**
* @param userid the userid to set
*/
public void setUserid(String userid) {
this.userid = userid;
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
}
IUserDaoImpl
package com.rock.spring.beans.annotation;
import org.springframework.stereotype.Repository;
@Repository
public class IUserDaoImpl implements IUserDao{
/**
* @Author :Rock
* @Date :2017年7月31日 下午4:53:09
* @TODO :
* @see com.rock.spring.beans.annotation.IUserDao#deleteUser(java.lang.String)
*/
@Override
public int deleteUser(String userid) {
System.out.println("IUserDaoImpl.deleteUser() is runnning....."+userid);
return 0;
}
}
IUserServiceImpl
package com.rock.spring.beans.annotation;
import javax.annotation.Resource;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
@Service
public class IUserServiceImpl implements IUserService{
@Resource
private IUserDao iUserDao;
/**
* @Author :Rock
* @Date :2017��7��31�� ����4:54:29
* @TODO :
* @see com.rock.spring.beans.annotation.IUserService#removeUser(com.rock.spring.beans.annotation.User)
*/
@Override
public int removeUser(User user) {
System.out.println("IUserServiceImpl.removeUser() is running......");
return iUserDao.deleteUser(user.getUserid());
}
}
UserAction.java
package com.rock.spring.beans.annotation;
import javax.annotation.Resource;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
/**
*
* FileName: com.rock.spring.beans.annotation UserAction.java
* TODO:
* Copyright: Copyright (c) 2015-2016 All Rights Reserved. Company: 01skill-soft.com Inc.
* @author: Rock
* @Date: 2017年7月31日:下午4:54:36
* @version: 1.0
*
* Modification History: Date Author Version Description
* ----------------------------------------------------------------------
* 2017年7月31日 Rock 1.0 1.0 Version
*
*/
@Controller
@Scope(value="singleton")
public class UserAction {
@Resource
private IUserService iUserService;
@Resource
private User user;
public void doGet(){
System.out.println("UserAction.doGet() is running.....");
iUserService.removeUser(user);
}
public String toString(){
return "UserAction is running.......";
}
}