Autowired vs import

BOTJr. :

I am very new to spring boot and I am trying to grasp the concept of it. Now I came across @Autowired in it. I understood pretty much about it.

Like, when you write @Autowired, things happen in two passes and in the second pass spring injects beans.

Now, I have this example;

Class Abc {

    @Autowired
    private Xyz xyz;

    PSVM(String...z) {
        xyz.hello();
    } 
}

Import basically imports the code into the file.

So,

Import com.tilak.Xyz;

Class Abc {
    private Xyz xyz;

    PSVM(String...z) {
        xyz = new Xyz();
        xyz.hello();
    }
}

Why should/ shouldn't I go with the latter one?

Is there any advantage in doing the first one? Where should I use the first one and where should I use the second one?

Damith :

Its basically about object creation. When you Autowire something, that particular bean is managed by the spring context and only one instance of particular class will be constructed by spring context and that particular instance will be provided when you use Autowire for that class type Objects. But when you import something into your class, that does not mean that you have an instance of that particular class; you have to initialize it on your own. And if you want to treat it as a singleton object, basically you will be writing whole code for it.

And more over there are basic differences between them like if you want to access static variables in a class, you will not need an instance of that class. (you can access them by class reference) In that case you dont need to Autowire but you need Import statement.

But on the other hand if you are interested in experiencing power of spring, like Autowire Configurations and may be validate them and all those cool functionalities that spring provides, you need to make your class a component and Autowire as you want.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=85042&siteId=1