使用Spring的Java Config,我需要使用只能在运行时获得的构造函数参数来获取/实例化原型范围的bean.请考虑以下代码示例(为简洁起见而简化):
@Autowired
private ApplicationContext appCtx;
public void onRequest(Request request) {
//request is already validated
String name = request.getParameter("name");
Thing thing = appCtx.getBean(Thing.class, name);
//System.out.println(thing.getName()); //prints name
}
Run Code Online (Sandbox Code Playgroud)
Thing类的定义如下:
public class Thing {
private final String name;
@Autowired
private SomeComponent someComponent;
@Autowired
private AnotherComponent anotherComponent;
public Thing(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
Run Code Online (Sandbox Code Playgroud)
注意事项name是final:它只能通过构造函数来提供,并保证不变性.其他依赖项是Thing类的特定于实现的依赖项,并且不应该知道(紧密耦合到)请求处理程序实现.
此代码与Spring XML配置完美配合,例如:
<bean id="thing", class="com.whatever.Thing" scope="prototype">
<!-- other post-instantiation properties omitted --> …Run Code Online (Sandbox Code Playgroud) 如果我有一个带有@PostConstruct方法的类,我如何使用JUnit和Spring测试其构造函数及其@PostConstruct方法?我不能简单地使用新的ClassName(param,param),因为它不使用Spring - @PostConstruct方法没有被触发.
我错过了一些明显的东西吗?
public class Connection {
private String x1;
private String x2;
public Connection(String x1, String x2) {
this.x1 = x1;
this.x2 = x2;
}
@PostConstruct
public void init() {
x1 = "arf arf arf"
}
}
@Test
public void test() {
Connection c = new Connection("dog", "ruff");
assertEquals("arf arf arf", c.getX1();
}
Run Code Online (Sandbox Code Playgroud)
我有类似的东西(虽然稍微复杂一些)并且@PostConstruct方法没有被击中.
我是Spring的新手,我使用https://start.spring.io/创建了一个新的spring boot项目,没有进一步的依赖关系,解压zip文件并在IntelliJ IDEA中打开项目.我还没有做进一步的配置.我现在正在尝试使用@PostConstruct方法设置bean - 但是,该方法永远不会被spring调用.
这些是我的课程:
SpringTestApplication.java
package com.habichty.test.testspring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class SpringTestApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(SpringTestApplication.class, args);
context.getBean(TestBean.class).testMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
TestBean.java
package com.habichty.test.testspring;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class TestBean {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private int a = 1;
public TestBean()
{
log.debug("Constructor of TestBean called.");
}
@PostConstruct
public void init()
{
log.debug("init()-Method of TestBean called."); …Run Code Online (Sandbox Code Playgroud)