[英]What is the proper way to have a “singleton” in Spring 4?
I have a java file "DatabaseMan.java" that helps connect to a database and connects helper functions. 我有一个Java文件“ DatabaseMan.java”,可帮助连接到数据库并连接帮助程序功能。 How can I make it such that it is created once for the life of my spring application, and I can call of its methods "getAllRows" for example, in each of my other resource classes?
如何使它在spring应用程序的生命周期内创建一次,并且可以在其他每个资源类中将其方法称为“ getAllRows”?
Should I be declaring a bean in my Application.java or using some sort of annotation on my "DatabaseMan" class to indicate that it is "injectable"/"resusable"? 我应该在Application.java中声明一个bean还是在“ DatabaseMan”类上使用某种注释来表明它是“可注入的” /“可重复使用的”?
I see the following Spring3 example: http://www.mkyong.com/spring3/spring-3-javaconfig-example/ 我看到以下Spring3示例: http ://www.mkyong.com/spring3/spring-3-javaconfig-example/
The issue is, do I have to include this within every single resource: 问题是,是否必须在每个资源中都包含此内容:
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
HelloWorld obj = (HelloWorld) context.getBean("helloBean");
obj.printHelloWorld("Spring3 Java Config");
Is there a better way to get to the "HelloWorld" with less code and more annotation in Spring 4? 在Spring 4中,有更少的代码和更多的注释可以更好地进入“ HelloWorld”吗?
Remember, the ApplicationContext
is a container to manage all your beans and their inter-dependencies. 请记住,
ApplicationContext
是用于管理所有bean及其相互依赖关系的容器。 It is the entry point to your application. 这是您的应用程序的入口点。 Once you've set it up, all the managed objects are linked up and ready to go.
设置好之后,所有托管对象都已链接好,可以使用了。
Is there a better way to get to the "HelloWorld" with less code and more annotation in Spring 4?
在Spring 4中,有更少的代码和更多的注释可以更好地进入“ HelloWorld”吗?
It depends where you want to get it. 这取决于您要在哪里获得它。 If you want to get it from outside the
ApplicationContext
, then you need to do what you did. 如果要从
ApplicationContext
外部获取它,则需要执行您的操作。 If you want to get into another bean, just inject it and the ApplicationContext
will do the rest. 如果您想进入另一个bean,只需注入它,其余的将由
ApplicationContext
完成。
@Component
class SomeOtherBean {
@Autowired
private HelloWorld helloWorldBean;
// do something with it
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.