如果您真的想使用构造函数创建对象,StudentWrapper
@Configurable
请阅读并阅读有关使用 AspectJ 为域对象创建原型 bean 定义(参考手册的第 9.8 节)。
如果您不想使用 AspectJ 但又不想直接依赖于 Spring,一个更简单的替代方法是将原型 bean 创建封装在工厂中。我将向您展示如何使用 JavaConfig,尽管您可以在 XML 中执行类似的操作。
首先是学生对象...
package internal;
public class Student {
private String name;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Student{name='" + name + "'}";
}
}
现在包装对象...
package internal;
public class StudentWrapper {
private Student student;
public StudentWrapper(Student student) {
this.student = student;
}
public Student getStudent() {
return student;
}
@Override
public String toString() {
return "StudentWrapper{student='" + student + "'} " + super.toString();
}
}
而现在的工厂,
package internal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class StudentWrapperFactory {
@Autowired
private ApplicationContext applicationContext;
public StudentWrapper newStudentWrapper(Student student) {
return (StudentWrapper) this.applicationContext.getBean("studentWrapper", student);
}
}
而现在的JavaConfig,相当于一个XML配置
package internal;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
@ComponentScan(basePackages = "internal")
public class FooConfig {
@Bean
@Scope("prototype")
public StudentWrapper studentWrapper(Student student) {
return new StudentWrapper(student);
}
}
最后是单元测试...
package internal;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {FooConfig.class})
public class FooIntegrationTest {
@Autowired
private StudentWrapperFactory studentWrapperFactory;
@Test
public void foo() {
Student student1 = new Student("student 1");
Student student2 = new Student("student 2");
StudentWrapper bean1 = this.studentWrapperFactory.newStudentWrapper(student1);
StudentWrapper bean2 = this.studentWrapperFactory.newStudentWrapper(student2);
System.out.println(bean1);
System.out.println(bean2);
}
}
生产
StudentWrapper{student='Student{name='student 1'}'} internal.StudentWrapper@1b0fa7ff
StudentWrapper{student='Student{name='student 2'}'} internal.StudentWrapper@20de643a
从 StudentWrapper 的对象引用中可以看出,它们是不同的原型 bean。@Transactional
方法应该按预期工作StudentWrapper
。