简体   繁体   中英

how to initialize a bean in spring container once and use it everywhere

actually i'm using spring for developing a web application, the problem i'm facing is that i'm initializing a bean as soon as the spring container is getting loaded, now i have to use that bean in different parts of my program. constraints that i have 1. i can get application context everywhere and get that bean but according to my problem i should get that bean without writing that redundant code again and again.so is there any way by which i can initialize that bean and use it directly everywhere in my program.

You should not get your bean from the context directly, instead you should @Autowire them and let Spring inject it for you.

Here's an example of two dependencies injected via constructor:

@Component
public class Car {

    private final Engine engine;
    private final Transmission transmission;

    @Autowired
    public Car(Engine engine, Transmission transmission) {
        this.engine = engine;
        this.transmission = transmission;
    }
}

Note that your class must be a Spring Component itself in order for the injection to occur.

There are actually three types of dependency injection in Spring: constructor, field and setter injection. Spring team recommends using the constructor based approach, and this post brings very nice arguments to this point: https://blog.marcnuri.com/field-injection-is-not-recommended/

You can refer to this link for more information on constructor-based injection: https://www.baeldung.com/constructor-injection-in-spring

If you already initialized your bean you can get access to it via @Autowired from each Component in your Spring Application.

private SomeClass myBean;

 @Autowired   
public void setMyBean(SomeClass myBean){
      this.myBean =myBean;
    }

Or just:

@Autowired
private SomeClass myBean;

I prefer the first method, looks fancier in my eyes.

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