Druudik
Druudik

Reputation: 1015

How can I autowired attributes of object which I created manually?

I have class which I created manually using new, because I needed to pass it some objects (not beans). It has 2 objects tough which I want to be autowired by spring. This is my class:

@Component
@Scope("prototype")
public class DayLayout extends VerticalLayout {

    @Autowired
    private SchedulingService schedulingService;

    @Autowired
    private GeneralService generalService;

    .
    .
    .
}

But after creation of the class those objects are still null. I think it is because I have not obtained that bean via spring container. But is there any way how can I create object manually and all it's objects will be still autowired ?

Upvotes: 0

Views: 1738

Answers (4)

Terry
Terry

Reputation: 927

I think you are misunderstanding some part of managed objects, but I am not sure what part that is.

Since you annotated the bean as @Prototype I assume you realize Spring will instantiate a new instance for you every time you request one. It would then be a trivial matter to call setters for your non-managed objects. You could even add a belt and suspenders approach and have your bean throw a IllegalStateException if the setters have not been called.

@Ivan is exactly correct on how you can manually request a bean. He is also exactly correct that if you are resorting to that your design is probably not the best.

Upvotes: 1

Ivan
Ivan

Reputation: 8758

So if you need to inject Autowired properties to an object created via new you could do the following:

DayLayout dl = new DayLayout(<whatever parameters go here>);
ctx.getAutowireCapableBeanFactory().autowireBean(dl); // Where ctx is Spring's application context

But if you need to do such things I think you might rethink what you are actually doing in your application.

Upvotes: 3

GabLeg
GabLeg

Reputation: 362

If you do : Object obj = new Object(); , it won't autowire. If you want to create manually your object, you can use a config file with @Configuration and return a @Bean. https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html . If that is not what you want, can you provide how you create those two objects ? What do you pass to them ?

Upvotes: 0

Lorelorelore
Lorelorelore

Reputation: 3393

Assuming that GeneralService is not a class annotated with @Component or other Spring stereotypes annotations: yes, there is.

@Configuration
public class ConfigClasses{

@Bean
public GeneralService generalService(){
    return new GeneralService();
    }

}

Obviously the same for SchedulingService, just add another method which produces that class.

Upvotes: 1

Related Questions