主方法类中的Springbean注入
我有一个使用Spring3.0的web应用程序。我需要从使用appcontext xml中定义的bean(使用组件扫描注释)的cron运行一个带有main方法的类。我的主类在同一个src目录中。 如何将web上下文中的bean注入到main方法中。我试着用主方法类中的Springbean注入,spring,dependency-injection,inversion-of-control,main,autowired,Spring,Dependency Injection,Inversion Of Control,Main,Autowired,我有一个使用Spring3.0的web应用程序。我需要从使用appcontext xml中定义的bean(使用组件扫描注释)的cron运行一个带有main方法的类。我的主类在同一个src目录中。 如何将web上下文中的bean注入到main方法中。我试着用 ApplicationContext context = new ClassPathXmlApplicationContext("appservlet.xml"); 我尝试使用AutoWired,它返回一个空bean。所以我使用了应用程序c
ApplicationContext context = new ClassPathXmlApplicationContext("appservlet.xml");
我尝试使用AutoWired,它返回一个空bean。所以我使用了应用程序ctx,这在我运行main方法时创建了一个新的上下文(如预期的那样)。但我是否可以使用容器中现有的bean呢
@Autowired
static DAO dao;
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("xman- servlet.xml");
TableClient client = context.getBean(TableClient.class);
client.start(context);
}
您可以为您的主应用程序使用spring上下文,并重用与webapp相同的bean。您甚至可以重用一些SpringXML配置文件,只要它们不定义仅在webapp上下文(请求范围、web控制器等)中有意义的bean
但是您将得到不同的实例,因为您将有两个JVM在运行。如果您真的想重用相同的bean实例,那么您的主类应该使用web服务或HttpInvoker远程调用webapp中bean的某些方法 您不能将Springbean注入任何非Spring创建的对象。另一种说法是:Spring只能注入到它所管理的对象中 因为您正在创建上下文,所以需要为DAO对象调用getBean
查看它可能对您有用。为了解决这个问题,我创建了一个。如果您喜欢建议的方法,请投赞成票。尝试以下主要方法:
public class Main {
public static void main(String[] args) {
Main p = new Main();
p.start(args);
}
@Autowired
private MyBean myBean;
private void start(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("classpath*:/META-INF/spring/applicationContext*.xml");
System.out.println("The method of my Bean: " + myBean.getStr());
}
}
这个豆子:
@Service
public class MyBean {
public String getStr() {
return "mybean!";
}
}
SpringBoot为此提供了一个正式的解决方案。从下载骨架
并确保pom.xml中的packaging设置为jar。只要不包含任何web依赖项,该应用程序将仍然是一个控制台应用程序。对于未来的读者,一个密切相关的问题: