使用注释配置Spring控制台应用程序 [英] Spring console application configured using annotations
问题描述
我想创建spring控制台应用程序(从maven的命令行运行,例如:mvn exec:java -Dexec.mainClass =package.MainClass)。
I want to create spring console application (running from command line with maven for example: mvn exec:java -Dexec.mainClass="package.MainClass").
是这个应用程序我想有某种服务和dao层。我知道如何做一个Web应用程序,但我没有找到任何信息,如果在一个控制台应用程序(可能与Swing)。
Is this application I want to have some kind of services and dao layers. I know how to do it for a web application but I have not found any information on how to do in case of a console application (leter maybe with Swing).
我'm尝试创建像:
public interface SampleService {
public String getHelloWorld();
}
@Service
public class SampleServiceImpl implements SampleService {
public String getHelloWorld() {
return "HelloWorld from Service!";
}
}
public class Main {
@Autowired
SampleService sampleService;
public static void main(String [] args) {
Main main = new Main();
main.sampleService.getHelloWorld();
}
}
有可能吗?
我可以在某处找到一个如何做的例子吗?
Is it possible? Can I find somewhere an example of how to do it?
推荐答案
a href =http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-instantiation> 3.2.2实例化容器。
Take a look at the Spring Reference, 3.2.2 Instantiating a container.
为了在控制台应用程序中使用Spring,您需要创建一个 ApplicationContext
In order to use Spring in console application you need to create an instance of ApplicationContext
and obtain Spring-managed beans from it.
在参考中描述了使用XML配置创建上下文。对于完全基于注释的方法,您可以这样做:
Creating a context using XML config is described in the Reference. For completely annotation-based approach, you can do someting like this:
@Component // Main is a Spring-managed bean too, since it have @Autowired property
public class Main {
@Autowired SampleService sampleService;
public static void main(String [] args) {
ApplicationContext ctx =
new AnnotationConfigApplicationContext("package"); // Use annotated beans from the specified package
Main main = ctx.getBean(Main.class);
main.sampleService.getHelloWorld();
}
}
这篇关于使用注释配置Spring控制台应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!