我想创建 spring 控制台应用程序(使用 maven 从命令行运行,例如:mvn exec:java -Dexec.mainClass="package.MainClass")。
我想要这个应用程序有某种服务和 dao 层吗?我知道如何为 Web 应用程序执行此操作,但我还没有找到任何有关如何在控制台应用程序(可能是 Swing)的情况下执行此操作的信息。
我正在尝试创建类似的东西:
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();
}
}
是否可以?
我可以在某处找到如何执行此操作的示例吗?
看看Spring参考,3.2.2 实例化容器 http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-instantiation.
为了在控制台应用程序中使用 Spring,您需要创建一个实例ApplicationContext
并从中获取 Spring 管理的 bean。
参考资料中描述了使用 XML 配置创建上下文。对于完全基于注释的方法,您可以执行以下操作:
@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();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)