Maven Pom.xml文件
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<junit.version>4.12</junit.version>
<spring.version>5.2.5.RELEASE</spring.version>
<mybatis.version>3.5.4</mybatis.version>
<mybatis.spring.version>2.0.4</mybatis.spring.version>
<mysql.version>5.1.48</mysql.version>
<commons-dbcp.version>2.7.0</commons-dbcp.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
applicationContext.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns: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">
<!--配置包扫描器 -->
<context:component-scan base-package="com.hlq.*" />
</beans>
配置单例模式(默认模式)
@Scope("singleton")
@Component("Customer")
public class Customer {
private Integer id;
private String username;
private String jobs;
private String phone;
}
测试
@Autowired
private Customer customer1;
@Autowired
private Customer customer2;
@Test
public void getCustomerPrototypeTest() {
customer1.setId(1);
customer2.setId(2);
System.out.println(customer1);
System.out.println(customer2);
}
Console:
Customer [id=2, username=null, jobs=null, phone=null]
Customer [id=2, username=null, jobs=null, phone=null]
原型模式注解为@Scope("prototype")
@Scope("prototype")
@Component("Customer")
public class Customer {
private Integer id;
private String username;
private String jobs;
private String phone;
}
测试
@Autowired
private Customer customer1;
@Autowired
private Customer customer2;
@Test
public void getCustomerPrototypeTest() {
customer1.setId(1);
customer2.setId(2);
System.out.println(customer1);
System.out.println(customer2);
}
Console:
Customer [id=1, username=null, jobs=null, phone=null]
Customer [id=2, username=null, jobs=null, phone=null]