创建maven项目
创建之后的项目骨架如图所示
配置pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>nansongling</groupId>
<artifactId>maven_spring_factory</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>maven_spring_factory Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.19.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>maven_spring_factory</finalName>
</build>
</project>
创建实例工厂(全部是非静态的方法)以及service层
项目骨架如下图所示
UserService.java
package maven_spring_service;
public interface UserService {
public void addUser();
}
UserServiceImpl.java
package maven_spring_service;
public class UserServiceImpl implements UserService {
public void addUser() {
System.out.println("sucess add user");
}
}
Facatory.java
package maven_spring_factory;
import maven_spring_service.UserServiceImpl;
public class Factory {
public UserServiceImpl getUserServiceImpl() {
return new UserServiceImpl();
}
}
配置applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd "
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<!-- 创建工厂实例 -->
<bean id="FactoryId" class="maven_spring_factory.Factory" ></bean>
<!-- 获得UserService
获得工厂实例
对象方法
-->
<bean id="UserServiceId" factory-bean="FactoryId" factory-method="getUserServiceImpl"></bean>
</beans>
创建test类进行测试
package maven_spring_factory;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import maven_spring_service.UserService;
import maven_spring_service.UserServiceImpl;
public class Test_Demo {
@Test
public void test() {
String xmlPath = "applicationContext.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
UserService userService = applicationContext.getBean("UserServiceId",UserServiceImpl.class);
userService.addUser();
}
}