一、Spring 框架高级应用
1.1 Spring 简介
1.2 Spring 框架特性
控制反转:Spring 通过一种称作控制反转(IoC)的技术促进了低耦合。当应用了 IoC,一个对象依赖的其它对象会通过被动的方式传递进来,而不是这个对象自己创建或者查找依赖对象。你可以认为 IoC 与 JNDI 相反——不是对象从容器中查找依赖,而是容器在对象初始化时不等对象请求就主动将依赖传递给它。它的底层设计模式采用了工厂模式,所有的 Bean 都需要注册到 Bean 工厂中,将其初始化和生命周期的监控交由工厂实现管理。程序员只需要按照规定的格式进行 Bean 开发,然后利用 XML 文件进行 bean 的定义和参数配置,其他的动态生成和监控就不需要调用者完成,而是统一交给了平台进行管理。 控制反转是软件设计大师 Martin Fowler 在2004年发表的 ” Inversion of Control Containers and the Dependency Injection pattern”提出的。这篇文章系统阐述了控制反转的思想,提出了控制反转有依赖查找和依赖注入实现方式。控制反转意味着在系统开发过程中,设计的类将交由容器去控制,而不是在类的内部去控制,类与类之间的关系将交由容器处理,一个类在需要调用另一个类时,只要调用另一个类在容器中注册的名字就可以得到这个类的实例,与传统的编程方式有了很大的不同,“不用你找,我来提供给你”,这就是控制反转的含义。
1.3 Spring 的特点
1.4 Spring 的优点
1.5 基本框架
1.6 组件
| | |
| ------ | ------------------------------------------------------------ |
| 类型 1 | 服务需要实现专门的接口,通过接口,由对象提供这些服务,可以从对象查询依赖性(例如,需要的附加服务)【接口注入】。 |
| 类型 2 | 通过 JavaBean 的属性(例如 setter 方法)分配依赖性【setter方法注入】。 |
| 类型 3 | 依赖性以构造函数的形式提供,不以 JavaBean 属性的形式公开【构造器注入】。 |
1.7 容器
二、基于 XML 配置文件的实现
2.1 基本使用
2.1.1 创建 Maven 工程





2.1.2 添加依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.17.RELEASE</version>
</dependency>
</dependencies>
<dependencies>
<!-- Spring相关依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.17.RELEASE</version>
</dependency>
<!-- junit 测试依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<?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">
</beans>
package com.gupaoedu.pojo;
public class HelloBean {
public HelloBean() {
System.out.println("HelloBean 无参构造被执行了......");
}
public void sayHello() {
System.out.println("Hello World! ");
}
}
<?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">
<!-- 添加需要被容器管理的bean -->
<bean id="userBean" class="com.gupaoedu.pojo.HelloBean" />
</beans>
package com.gupaoedu.test;
import com.gupaoedu.pojo.HelloBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloTest {
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloBean hello = (HelloBean)ac.getBean("userBean");
hello.sayHello();
}
}
2.1.3 从容器中获取对象的方式
2.1.3.1 根据 id 获取
<?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">
<!-- 添加需要被容器管理的bean -->
<bean id="userBean1,userBean2" class="com.gupaoedu.pojo.HelloBean" />
</beans>
package com.gupaoedu.test;
import com.gupaoedu.pojo.HelloBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloTest {
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloBean hello = (HelloBean)ac.getBean("userBean1,userBean2");
hello.sayHello();
}
}
2.1.3.2 根据name获取
可以声明一个或者多个name,多个name之间可以用','(逗号)、';'(分号)、' '(空格)隔开。
<?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">
<!-- 添加需要被容器管理的bean -->
<bean id="userBean1,userBean2" name="ub1,bu2" class="com.gupaoedu.pojo.HelloBean" />
</beans>
package com.gupaoedu.test;
import com.gupaoedu.pojo.HelloBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloTest {
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloBean h1 = (HelloBean)ac.getBean("ub1");
HelloBean h2 = (HelloBean)ac.getBean("ub2");
h1.sayHello();
h2.sayHello();
}
}
2.1.3.3 根据类型获取
<?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">
<!-- 添加需要被容器管理的bean -->
<bean id="userBean1,userBean2" name="ub1,bu2" class="com.gupaoedu.pojo.HelloBean" />
</beans>
package com.gupaoedu.test;
import com.gupaoedu.pojo.HelloBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloTest {
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloBean hello = ac.getBean(HelloBean.class);
hello.sayHello();
}
}
2.1.3.4 组合条件查找
<?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">
<!-- 添加需要被容器管理的bean -->
<bean id="userBean1,userBean2" name="ub1,ub2" class="com.gupaoedu.pojo.HelloBean" />
<bean id="userBean3,userBean4" name="ub3,ub4" class="com.gupaoedu.pojo.HelloBean" />
</beans>
package com.gupaoedu.test;
import com.gupaoedu.pojo.HelloBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloTest {
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloBean hello = ac.getBean("ub1", HelloBean.class);
hello.sayHello();
}
}
2.1.4 BeanFactory 和 ApplicationContext 的区别
2.1.5 工厂注入
2.1.5.1 静态工厂注入
<?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">
<!-- 通过静态工厂方式注入 -->
<bean class="com.gupaoedu.com.gupaoedu.factory.StaticFactoryDemo" factory-method="getInstance" id="hello" />
</beans>
package com.gupaoedu.com.gupaoedu.factory;
import com.gupaoedu.pojo.HelloBean;
import java.util.HashMap;
import java.util.Map;
public class StaticFactory {
public static Map<String, HelloBean> hashMap ;
static {
hashMap = new HashMap<String, HelloBean>();
hashMap.put("h1",new HelloBean());
hashMap.put("h2",new HelloBean());
hashMap.put("h3",new HelloBean());
}
public static HelloBean getInstance(){
return hashMap.get("h1");
}
}
2.1.5.2 动态工厂注入
<?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">
<!-- 通过动态工厂方式注入 -->
<bean class="com.gupaoedu.com.gupaoedu.factory.DynamicFactoryDemo" id="dynamicFactoryDemo" />
<!-- 从工程费对象中获取 需要的对象 -->
<bean id="hello2" factory-bean="dynamicFactoryDemo" factory-method="getInstanc" />
</beans>
package com.gupaoedu.com.gupaoedu.factory;
import com.gupaoedu.pojo.HelloBean;
public class DynamicFactoryDemo {
public HelloBean getInstanc() {
return new HelloBean();
}
}
2.1.6 属性注入(DI)
2.1.6.1 构造方法注入
package com.gupaoedu.pojo;
public class UserBean {
private Integer id;
private String userName;
public UserBean() {
}
public UserBean(Integer id, String userName) {
this.id = id;
this.userName = userName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public String toString() {
return "UserBean{" +
"id=" + id +
", userName='" + userName + '\'' +
'}';
}
}
<?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">
<bean class="com.gupaoedu.pojo.UserBean" id="user">
<!-- 构造注入 - 通过name赋值 -->
<constructor-arg name="id" value="1" />
<constructor-arg name="userName" value="张三 " />
</bean>
</beans>
package com.gupaoedu.test;
import com.gupaoedu.pojo.UserBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserTest {
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-01.xml");
UserBean user = ac.getBean("user", UserBean.class);
System.out.println(user);
}
}
<?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">
<bean class="com.gupaoedu.pojo.UserBean" id="user">
<!-- 构造注入 - 通过name赋值 -->
<!--<constructor-arg name="id" value="1" />
<constructor-arg name="userName" value="张三 " />-->
<!-- 构造注入 - 通过index赋值 -->
<constructor-arg index="0" value="2" />
<constructor-arg index="1" value="李四" />
</bean>
</beans>
<?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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.gupaoedu.pojo.UserBean" id="user" c:_0="4" c:_1="赵六"/>
</beans>
2.1.6.2 set 方法注入
<?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">
<bean class="com.gupaoedu.pojo.UserBean" id="user">
<!-- set注入 -->
<property name="id" value="3"/>
<property name="userName" value="王五"/>
</bean>
</beans>
package com.gupaoedu.test;
import com.gupaoedu.pojo.UserBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserTest {
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-01.xml");
UserBean user = ac.getBean("user", UserBean.class);
System.out.println(user);
}
}
<?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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.gupaoedu.pojo.UserBean" id="user" p:id="5" p:userName="孙七"/>
</beans>
2.1.7 其他注入
2.1.7.1 自定义类型
package com.gupaoedu.pojo;
public class Cat {
private String nick;
private String color;
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Cat() {
}
public Cat(String nick, String color) {
this.nick = nick;
this.color = color;
}
@Override
public String toString() {
return "Cat{" +
"nick='" + nick + '\'' +
", color='" + color + '\'' +
'}';
}
}
package com.gupaoedu.pojo;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class UserBean {
private Integer id;
private String userName;
private Cat cat;
private String[] favorites;
private List<Cat> cats;
private Map<String, Object> map;
private Properties props;
public UserBean() {
}
public UserBean(Integer id, String userName) {
this.id = id;
this.userName = userName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public String[] getFavorites() {
return favorites;
}
public void setFavorites(String[] favorites) {
this.favorites = favorites;
}
public List<Cat> getCats() {
return cats;
}
public void setCats(List<Cat> cats) {
this.cats = cats;
}
public Map<String, Object> getMap() {
return map;
}
public void setMap(Map<String, Object> map) {
this.map = map;
}
public Properties getProps() {
return props;
}
public void setProps(Properties props) {
this.props = props;
}
@Override
public String toString() {
return "UserBean{" +
"id=" + id +
", userName='" + userName + '\'' +
", cat=" + cat +
", favorites=" + Arrays.toString(favorites) +
", cats=" + cats +
", map=" + map +
", props=" + props +
'}';
}
}
<?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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.gupaoedu.pojo.Cat" p:nick="花花" p:color="黑色" id="cat" />
<bean class="com.gupaoedu.pojo.UserBean" id="user">
<property name="cat" ref="cat">
<!--<bean class="com.gupaoedu.pojo.Cat" p:nick="花花" p:color="黑色" />-->
</property>
</bean>
</beans>
<?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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.gupaoedu.pojo.UserBean" id="user">
<property name="cat">
<bean class="com.gupaoedu.pojo.Cat" p:nick="花花" p:color="黑色" />
</property>
</bean>
</beans>
<?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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.gupaoedu.pojo.UserBean" id="user">
<property name="cat">
<bean class="com.gupaoedu.pojo.Cat" p:nick="花花" p:color="黑色" />
</property>
<property name="favorites">
<array>
<value>游戏</value>
<value>音乐</value>
<value>看书</value>
</array>
</property>
</bean>
</beans>
package com.gupaoedu.test;
import com.gupaoedu.pojo.UserBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserTest {
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-01.xml");
UserBean user = ac.getBean("user", UserBean.class);
System.out.println(user.getCat());
String[] favorites = user.getFavorites();
for(String f : favorites) {
System.out.println(f);
}
}
}
2.1.7.2 数组
<?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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.gupaoedu.pojo.UserBean" id="user">
<property name="cat">
<bean class="com.gupaoedu.pojo.Cat" p:nick="花花" p:color="黑色" />
</property>
<property name="favorites">
<array>
<value>游戏</value>
<value>音乐</value>
<value>看书</value>
</array>
</property>
<property name="cats">
<list>
<bean class="com.gupaoedu.pojo.Cat" p:nick="花花" p:color="黑色"/>
<bean class="com.gupaoedu.pojo.Cat" p:nick="小白" p:color="白色"/>
<bean class="com.gupaoedu.pojo.Cat" p:nick="毛团" p:color="灰色"/>
</list>
</property>
</bean>
</beans>
package com.gupaoedu.test;
import com.gupaoedu.pojo.UserBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserTest {
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-01.xml");
UserBean user = ac.getBean("user", UserBean.class);
System.out.println(user.getCat());
String[] favorites = user.getFavorites();
for(String f:favorites) {
System.out.println(f);
}
System.out.println(user.getCats());
}
}
2.1.7.3 Map
<?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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.gupaoedu.pojo.UserBean" id="user">
<property name="cat">
<bean class="com.gupaoedu.pojo.Cat" p:nick="花花" p:color="黑色" />
</property>
<property name="favorites">
<array>
<value>游戏</value>
<value>音乐</value>
<value>看书</value>
</array>
</property>
<property name="cats">
<list>
<bean class="com.gupaoedu.pojo.Cat" p:nick="花花" p:color="黑色"/>
<bean class="com.gupaoedu.pojo.Cat" p:nick="小白" p:color="白色"/>
<bean class="com.gupaoedu.pojo.Cat" p:nick="毛团" p:color="灰色"/>
</list>
</property>
<property name="map">
<map>
<entry key="name1" value="张三"/>
<entry key="name2" value="李四"/>
<entry key="name3" value="王五"/>
</map>
</property>
</bean>
</beans>
package com.gupaoedu.test;
import com.gupaoedu.pojo.UserBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Set;
public class UserTest {
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-01.xml");
UserBean user = ac.getBean("user", UserBean.class);
System.out.println(user.getCat());
String[] favorites = user.getFavorites();
for(String f:favorites) {
System.out.println(f);
}
System.out.println(user.getCats());
Set<String> maps = user.getMap().keySet();
for(String key:maps) {
System.out.println(key + ":" + user.getMap().get(key));
}
}
}
2.1.7.4 Properties
<?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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="com.gupaoedu.pojo.UserBean" id="user">
<property name="cat">
<bean class="com.gupaoedu.pojo.Cat" p:nick="花花" p:color="黑色" />
</property>
<property name="favorites">
<array>
<value>游戏</value>
<value>音乐</value>
<value>看书</value>
</array>
</property>
<property name="cats">
<list>
<bean class="com.gupaoedu.pojo.Cat" p:nick="花花" p:color="黑色"/>
<bean class="com.gupaoedu.pojo.Cat" p:nick="小白" p:color="白色"/>
<bean class="com.gupaoedu.pojo.Cat" p:nick="毛团" p:color="灰色"/>
</list>
</property>
<property name="map">
<map>
<entry key="name1" value="张三"/>
<entry key="name2" value="李四"/>
<entry key="name3" value="王五"/>
</map>
</property>
<property name="props">
<props>
<prop key="username">root</prop>
<prop key="password">1234</prop>
</props>
</property>
</bean>
</beans>
package com.gupaoedu.test;
import com.gupaoedu.pojo.UserBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Properties;
import java.util.Set;
public class UserTest {
@Test
public void test() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext-01.xml");
UserBean user = ac.getBean("user", UserBean.class);
System.out.println(user.getCat());
String[] favorites = user.getFavorites();
for(String f:favorites) {
System.out.println(f);
}
System.out.println(user.getCats());
Set<String> maps = user.getMap().keySet();
for(String key:maps) {
System.out.println(key + ":" + user.getMap().get(key));
}
Properties props = user.getProps();
System.out.println(props.getProperty("username"));
System.out.println(props.getProperty("password"));
}
}
三、基于注解编程
3.1 综合案例
package com.gupaoedu;
import com.gupaoedu.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JavaConfig {
/**
* @Bean 作用相当于applicationContext.xml中的<bean>
* 默认的name是方法名称
* 自定义的name 可以通过value属性或者name属性来指定
* @return
*/
@Bean(name = {"aaa","bbb"})
public User getUser() {
return new User();
}
}
package com.gupaoedu.test;
import com.gupaoedu.JavaConfig;
import com.gupaoedu.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainTest {
@Test
public void test() {
// 通过@Configuration注解来初始化IoC容器
ApplicationContext ac = new AnnotationConfigApplicationContext(JavaConfig.class);
System.out.println(ac.getBean("bbb", User.class));
}
}
3.1.1 基于 XML 方式的实现
package com.gupaoedu.pojo;
public class User {
private Integer id;
private String userName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public User() {
}
public User(Integer id, String userName) {
this.id = id;
this.userName = userName;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
'}';
}
}
package com.gupaoedu.controller;
import com.gupaoedu.pojo.User;
import com.gupaoedu.service.IUserService;
import java.util.List;
public class UserController {
private IUserService userService;
public void setUserService(IUserService userService) {
this.userService = userService;
}
public List<User> query(){
return userService.query();
}
}
package com.gupaoedu.dao;
import com.gupaoedu.pojo.User;
import java.util.List;
public interface IUserDao {
public List<User> query();
}
package com.gupaoedu.dao.impl;
import com.gupaoedu.dao.IUserDao;
import com.gupaoedu.pojo.User;
import java.util.Arrays;
import java.util.List;
public class UserDaoImpl implements IUserDao {
public List<User> query() {
return Arrays.asList(
new User(1, "张三"),
new User(2, "李四"),
new User(3, "王五"),
new User(4, "赵六"));
}
}
package com.gupaoedu.service;
import com.gupaoedu.pojo.User;
import java.util.List;
public interface IUserService {
public List<User> query();
}
package com.gupaoedu.service.impl;
import com.gupaoedu.dao.IUserDao;
import com.gupaoedu.pojo.User;
import com.gupaoedu.service.IUserService;
import java.util.List;
public class UserServiceImpl implements IUserService {
private IUserDao userDao;
public void setUserDao(IUserDao userDao) {
this.userDao = userDao;
}
public List<User> query() {
return userDao.query();
}
}
<?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">
<!-- 将Dao对象注册到容器中 -->
<bean class="com.gupaoedu.dao.impl.UserDaoImpl" id="userDao"></bean>
<!-- 将Service对象注册到容器中 -->
<bean class="com.gupaoedu.service.impl.UserServiceImpl" id="userService">
<!-- 通过Set注入的方式引入Dao对象 -->
<property name="userDao" ref="userDao" />
</bean>
<!-- 将Controller对象注册到容器中 -->
<bean class="com.gupaoedu.controller.UserController">
<!-- 通过Set注入的方式引入Service对象 -->
<property name="userService" ref="userService" />
</bean>
</beans>
package com.gupaoedu;
import com.gupaoedu.controller.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppStarter {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserController bean = ac.getBean(UserController.class);
System.out.println(bean.query());
}
}
3.1.2 基于 Java 配置的方式实现
package com.gupaoedu.pojo;
public class User {
private Integer id;
private String userName;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public User() {
}
public User(Integer id, String userName) {
this.id = id;
this.userName = userName;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
'}';
}
}
package com.gupaoedu.controller;
import com.gupaoedu.pojo.User;
import com.gupaoedu.service.IUserService;
import java.util.List;
public class UserController {
private IUserService userService;
public void setUserService(IUserService userService) {
this.userService = userService;
}
public List<User> query(){
return userService.query();
}
}
package com.gupaoedu.dao;
import com.gupaoedu.pojo.User;
import java.util.List;
public interface IUserDao {
public List<User> query();
}
package com.gupaoedu.dao.impl;
import com.gupaoedu.dao.IUserDao;
import com.gupaoedu.pojo.User;
import java.util.Arrays;
import java.util.List;
public class UserDaoImpl implements IUserDao {
public List<User> query() {
return Arrays.asList(
new User(1, "张三"),
new User(2, "李四"),
new User(3, "王五"),
new User(4, "赵六"));
}
}
package com.gupaoedu.service;
import com.gupaoedu.pojo.User;
import java.util.List;
public interface IUserService {
public List<User> query();
}
package com.gupaoedu.service.impl;
import com.gupaoedu.dao.IUserDao;
import com.gupaoedu.pojo.User;
import com.gupaoedu.service.IUserService;
import java.util.List;
public class UserServiceImpl implements IUserService {
private IUserDao userDao;
public void setUserDao(IUserDao userDao) {
this.userDao = userDao;
}
public List<User> query() {
return userDao.query();
}
}
package com.gupaoedu;
import com.gupaoedu.controller.UserController;
import com.gupaoedu.dao.IUserDao;
import com.gupaoedu.dao.impl.UserDaoImpl;
import com.gupaoedu.service.IUserService;
import com.gupaoedu.service.impl.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JavaConfig {
@Bean
public IUserDao userDao() {
return new UserDaoImpl();
}
@Bean
public IUserService userService(IUserDao userDao) {
IUserService userService = new UserServiceImpl();
((UserServiceImpl) userService).setUserDao(userDao);
return userService;
}
@Bean
public UserController userController(IUserService userService) {
UserController userController = new UserController();
userController.setUserService(userService);
return userController;
}
}
package com.gupaoedu;
import com.gupaoedu.controller.UserController;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AppStarter {
public static void main(String[] args) {
ApplicationContext ac = new AnnotationConfigApplicationContext(JavaConfig.class);
System.out.println(ac.getBean(UserController.class).query());
}
}
3.2 注解
3.2.1 配置注解
| 注解名称 | 说明 |
| -------------- | ------------------------------------------------------------ |
| @Configuration | 把一个类作为一个IoC容器,它的某个方法头上如果注册了@Bean,就会作为这个Spring容器中的Bean。 |
| @ComponentScan | 在配置类上添加 @ComponentScan 注解。该注解默认会扫描该类所在的包下所有的配置类,相当于之前的 <context:component-scan> |
| @Scope | 用于指定scope作用域的(用在类上) |
| @Lazy | 表示延迟初始化 |
| @Conditional | Spring4开始提供,它的作用是按照一定的条件进行判断,满足条件给容器注册Bean。 |
| @Import | 导入外部资源 |
| 生命周期控制 | @PostConstruct用于指定初始化方法(用在方法上)@PreDestory用于指定销毁方法(用在方法上)@DependsOn:定义Bean初始化及销毁时的顺序 |
| @Conditional扩展注解 | 作用(判断是否满足当前指定条件) |
| ------------------------------- | ------------------------------------------------ |
| @ConditionalOnJava | 系统的Java版本是否符合要全 |
| @ConditionalOnBean | 容器中存在指定的Bean |
| @ConditionalOnMissingBean | 容器中不存在指定的Bean |
| @ConditionalOnExpression | 满足SpEL表达式 |
| @ConditionalOnClass | 系统中有指定的类 |
| @ConditionalOnMissingClass | 系统中没有指定的类 |
| @ConditionalOnSingleCandidate | 容器中只有一个指定的Bean,或者这个Bean是首选Bean |
| @ConditionalOnProperty | 系统中指定的属性是否有指定的值 |
| @ConditionalOnResource | 类路径下是否存在指定的资源文件 |
| @ConditionalOnWebApplication | 当前是Web环境 |
| @ConditionalOnNotWebApplication | 当前不是Web环境 |
| @ConditionalOnJndi | JNDI存在指定项 |
3.2.2 赋值注解
| 注解名称 | 说明 |
| --------------- | ------------------------------------------------------------ |
| @Component | 泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。 |
| @Service | 用于标注业务层组件 |
| @Controller | 用于标注控制层组件 |
| @Repository | 用于标注数据访问组件,即DAO组件。 |
| @Value | 普通数据类型赋值 |
| @Autowired | 默认按类型装配,如果我们想使用按名称装配,可以结合@Qualifier注解一起使用 |
| @PropertySource | 读取配置文件赋值 |
| @Qualifier | 如存在多个实例配合使用 |
| @Primary | 自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常 |
| @Resource | 默认按名称装配,当找不到与名称匹配的bean才会按类型装配。 |
3.3 注解编程的使用
3.3.1 基于 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.xsd
">
<!-- 添加扫描的路径 指定从哪些package下加载被 @Component标注的类型-->
<!--<context:component-scan base-package="com.gupaoedu"/>-->
<!--<context:component-scan base-package="com.gupaoedu.controller
,com.gupaoedu.service.impl
,com.gupaoedu.dao.impl"/>-->
<context:component-scan base-package="com.gupaoedu.controller" />
<context:component-scan base-package="com.gupaoedu.service.impl" />
<context:component-scan base-package="com.gupaoedu.dao.impl" />
</beans>
<?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.xsd
">
<!-- 添加扫描的路径 指定从哪些package下加载被 @Component标注的类型-->
<!--<context:component-scan base-package="com.gupaoedu"/>-->
<!--<context:component-scan base-package="com.gupaoedu.controller
,com.gupaoedu.service.impl
,com.gupaoedu.dao.impl"/>-->
<!--
use-default-filters="false" 表示不适用默认的过滤器
默认过滤器会识别 @Componenet @Controller @Service @Repository
-->
<context:component-scan base-package="com.gupaoedu.controller" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<context:component-scan base-package="com.gupaoedu.service.impl,com.gupaoedu.dao.impl" use-default-filters="true" >
<!-- 排除掉某个注解 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
</beans>
3.3.2 基于 Java 配置的方式实现
package com.gupaoedu;
import com.gupaoedu.controller.UserController;
import com.gupaoedu.dao.IUserDao;
import com.gupaoedu.dao.impl.UserDaoImpl;
import com.gupaoedu.service.IUserService;
import com.gupaoedu.service.impl.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
/**
* @ComponentScan 如果不去指定扫描的路基,默认是会扫描当前目录及其子目录下的所有的
* 被@Componenet @Controller @Service @Repository标注的类型
*/
@Configuration
/*@ComponentScan(value = {"com.gupaoedu.controller"}
,useDefaultFilters = false
,includeFilters = {@ComponentScan.Filter(Controller.class)})*/
@ComponentScans({
@ComponentScan(value = {"com.gupaoedu.controller"}
,useDefaultFilters = false
,includeFilters = {@ComponentScan.Filter(Controller.class)})
,@ComponentScan(value = {"com.gupaoedu.service","com.gupaoedu.dao"}
,useDefaultFilters = true
,excludeFilters = {@ComponentScan.Filter(Controller.class)})
})
public class JavaConfig {
}
3.3.3 @Value 注解介绍
package com.gupaoedu.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
/**
* 让每一个人的职业生涯不留遗憾
*
* @author 波波老师【咕泡学院】
*/
@Component
public class User {
@Value("张三") // 注入普通的字符串
private String userName ;
@Value("#{systemProperties['os.name']}")
private String systemPropertiesName; // 注入操作系统的信息
@Value("#{T(java.lang.Math).random()*100}")
private double randomNumber; // 注入表达式的结果
@Value("#{person.personName}")
private String fromPersonName; // 注入其他Bean的属性
@Value("classpath:test.txt")
private Resource resourceFile;
@Value("http://www.baidu.com")
private Resource baiduFile;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSystemPropertiesName() {
return systemPropertiesName;
}
public void setSystemPropertiesName(String systemPropertiesName) {
this.systemPropertiesName = systemPropertiesName;
}
public double getRandomNumber() {
return randomNumber;
}
public void setRandomNumber(double randomNumber) {
this.randomNumber = randomNumber;
}
public String getFromPersonName() {
return fromPersonName;
}
public void setFromPersonName(String fromPersonName) {
this.fromPersonName = fromPersonName;
}
public Resource getResourceFile() {
return resourceFile;
}
public void setResourceFile(Resource resourceFile) {
this.resourceFile = resourceFile;
}
public Resource getBaiduFile() {
return baiduFile;
}
public void setBaiduFile(Resource baiduFile) {
this.baiduFile = baiduFile;
}
@Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
", systemPropertiesName='" + systemPropertiesName + '\'' +
", randomNumber=" + randomNumber +
", fromPersonName='" + fromPersonName + '\'' +
", resourceFile=" + resourceFile +
", baiduFile=" + baiduFile +
'}';
}
}
package com.gupaoedu.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Person {
@Value("PersonInfo")
private String personName;
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
}
package com.gupaoedu.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.gupaoedu")
public class JavaConfig {
}
public class AppStarter {
public static void main(String[] args) {
ApplicationContext ac = new AnnotationConfigApplicationContext(JavaConfig.class);
System.out.println(ac.getBean(User.class));
User user = ac.getBean(User.class);
}
}
717

被折叠的 条评论
为什么被折叠?



