Spring bean加载的三种方式
UserService:
package com.njtech.service;
public interface UserService {
public void add();
}
UserServiceImpl:
package com.njtech.service.Impl;
import com.njtech.service.UserService;
/**
* 〈一句话功能简述〉:UserService 的实现类
* @author njtech
* @create 2019/6/8
* @since 1.0.0
*/
public class UserServiceImpl implements UserService {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void add(){
System.out.println("创建新用户........."+name);
}
}
bean.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: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.xsd">
<bean id="userService" class="com.njtech.service.Impl.UserServiceImpl">
<!--依赖注入数据,调用属性的set方法-->
<property name="name" value="张三"></property>
</bean>
</beans>
Day01Test :
package com.njtech.test;
import com.njtech.service.Impl.UserServiceImpl;
import com.njtech.service.UserService;
import javafx.application.Application;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
/**
* 〈一句话功能简述〉:spring加载的三种方式,其中第一种方式最常用
*
* @author njtech
* @create 2019/6/8
* @since 1.0.0
*/
public class Day01Test {
@Test
public void test(){
//第一种方式:ClassPathXmlApplicationContext
ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
UserService userService=(UserService) context.getBean("userService");
userService.add();
System.out.println(userService);
System.out.println(".................................");
//第二种方式:通过文件系统路径获得配置文件 【绝对路径】
ApplicationContext context1=new FileSystemXmlApplicationContext("G:\\project\\day02-spring-njtech\\src\\bean.xml");
UserService userService1=(UserService) context.getBean("userService");
userService1.add();
System.out.println(userService1);
System.out.println(".................................");
//第三种方式:使用BeanFactory
String path="G:\\project\\day02-spring-njtech\\src\\bean.xml";
BeanFactory factory=new XmlBeanFactory(new FileSystemResource(path));
UserService userService2=(UserService) factory.getBean("userService");
userService2.add();
System.out.println(userService2);
}
}
BeanFactory 和ApplicationContext 的区别:
(1)BeanFactory 采取延迟加载,第一次getBean时才会初始化Bean
(2)ApplicationContext 即时加载
ApplicationContext是对BeanFactory扩展,提供了更多功能:
A.国际化处理
B.事件传递
C.Bean自动装配
D.各种不同应用层的Context实现