Java Spring-如何在不调用ClassPathXmlApplicationContext的情况下@Autowire一个bean
是否可以在不调用以下命令的情况下自动连接bean:Java Spring-如何在不调用ClassPathXmlApplicationContext的情况下@Autowire一个bean,java,spring,autowired,Java,Spring,Autowired,是否可以在不调用以下命令的情况下自动连接bean: ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 如果您的意思是没有xml conifg,请尝试此测试 class T1 { } class T2 { @Autowired T1 t1; } public class Main { public static void main(St
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
如果您的意思是没有xml conifg,请尝试此测试
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中否。至少需要创建一个Spring上下文来自动连接或从上下文中执行依赖项注入。这是一个独立的应用程序,您应该了解,所有自动连接的bean首先必须由Spring管理,然后才发生其他事情。