小编ger*_*ard的帖子

当使用构造函数参数自动装配原型bean时,为什么不调用@PostConstruct方法

我有一个原型范围bean,我希望通过@Autowired注释注入它.在这个bean中,还有@PostConstruct方法,Spring没有调用它,我不明白为什么.

我的bean定义:

package somepackage;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@Component
@Scope("prototype")
public class SomeBean {

    public SomeBean(String arg) {
        System.out.println("Constructor called, arg: " + arg);
    }

    @PostConstruct
    private void init() {
        System.out.println("Post construct called");
    }

}
Run Code Online (Sandbox Code Playgroud)

我想要注入bean的JUnit类:

package somepackage;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@ContextConfiguration("classpath*:applicationContext-test.xml")
public class SomeBeanTest {

    @Autowired
    ApplicationContext ctx;

    @Autowired
    @Value("1")
    private SomeBean someBean;

    private SomeBean someBean2;

    @Before
    public void setUp() throws Exception { …
Run Code Online (Sandbox Code Playgroud)

java spring postconstruct prototype-scope

20
推荐指数
2
解决办法
4339
查看次数

标签 统计

java ×1

postconstruct ×1

prototype-scope ×1

spring ×1