michealAtmi
michealAtmi

Reputation: 1042

Java AOP set field value while constructing object

I am using Spring and Java 8. I would like to create an aspect or something like that that would set value of my field during object construction, the constructor itsleft validates if the field is not null so the value has to be set accordingly, is it possible with aspects ?

protected MyObject(TimeProvider timeProvider) {
        this.timeProvider = requireNonNull(timeProvider, " cannot be null");
        requireNonNull(someField, "someFieldcannot be null");

Here u can see that someField is required during creation and not specified in list of fields in the constructor. Thats my specific case.

Upvotes: 0

Views: 646

Answers (2)

Antoniossss
Antoniossss

Reputation: 32507

You can use BeanFactory to either

  1. Create new (non singleton) instance of of given class - injection will be done for your
  2. Perform injections on already existing object.

In both cases @Autowire + @NotNull on setter/field should do the trick.

Check https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/config/AutowireCapableBeanFactory.html#autowireBean-java.lang.Object- for example or any other variants.

Upvotes: 0

Mark Bramnik
Mark Bramnik

Reputation: 42441

There is something in the question that doesn't sound right, I'll explain...

Spring AOP indeed allows to create aspects that will wrap Spring beans. They're completely irrelevant for non-spring managed objects.

Now if you're talking about Spring Bean: MyObject then spring will create the instance of this object and inject the TimeProvider - an another bean. If this TimeProvider doesn't exist, spring context will fail to start, thats exactly what you're trying to achieve. You're already using constructor injection so this should work as long as MyObject is a spring bean. Obviously in this case you don't need any aspects, spring will do all the job for you.

Alternatively if MyObject is not a spring bean then spring-aop is completely irrelevant as I've explained.

Its possible to go deeper and analyze how Spring AOP really works and you'll realize that they don't do exactly validations like this, but again, this is rather more advaned discussion than required in order to answer this question

Upvotes: 1

Related Questions