简体   繁体   中英

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. 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?

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"?

I see the following Spring3 example: 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?

Remember, the ApplicationContext is a container to manage all your beans and their inter-dependencies. 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?

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. If you want to get into another bean, just inject it and the ApplicationContext will do the rest.

@Component
class SomeOtherBean {
    @Autowired
    private HelloWorld helloWorldBean;

    // do something with it
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM