Spring - 如何@Autowire bean而不调用ClassPathXmlApplicationContext

时间:2013-04-09 05:59:02

标签: java spring autowired

是否可以在不调用的情况下自动装配bean:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

1 个答案:

答案 0 :(得分:1)

如果您的意思是no-xml配置,请尝试此测试

class T1 {
}

class T2 {
    @Autowired
    T1 t1;
}

public class Main {

    public static void main(String[] args) throws Exception {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.register(T1.class, T2.class);
        ctx.refresh();
        System.out.println(ctx.getBean(T2.class).t1);
    }
}

它将显示T1 bean被注入T2 bean