1

I am trying to autowire Optional in a component. Object is in custom ThreadScope and proxy-mode = INTERFACES.

I think @Autowired Optional<ObjectType> objectTypeOptional just ensures that Autowiring is not requried. Now objectTypeOptional.isPresnet() always returns true. Because there is a proxy for ObjectType. Is there a way to say that objectTypeOptional is not present?

Post Edit (Adding more context to the question):

My bean is something like this -

@Component
public User {
    private final userName;
    private final userEmail;
    // constructors and getters
}

Now I want to inject Optional of User in any service or controller. Something like - @Autowired Optional<User> userOptional;

So whenever a user is logged in, a filter/interceptor will create an appropriate User object. But when no user is logged in I should be able to check it via optional - userOptional.isPresent()

1 Answers1

1

I believe Provider would be more fit for you.

Java Docs

You would autowire

@Resource
Provider<UsersConnectionRepository> usersConnectionRepositoryProvider;

and have a method or call get() on the Provider

private UsersConnectionRepository getUserConnectionRepository() {
    return usersConnectionRepositoryProvider.get();
  }

Also you can do @Autowired(required = false).

Vaelyr
  • 2,841
  • 2
  • 21
  • 34
  • I actually want a way to figure out if the object is present or not. For example I create a `User` object whenever there is logged in user. Otherwise the `User` object is null. So if I can inject `Optional` I can then check if the `User` is present or not before accessing it. – Siddharth Prakash Singh Jul 18 '15 at 15:29
  • If you make the user then you can make Optional yourself as well using its methods `Optional.of(..)` or `Optional.ofNullable(..)`. – Vaelyr Jul 18 '15 at 18:19
  • I am sorry. I still didn't understand your solution totally. Are you saying - `@Autowired Provider> optionalUserProvider;` and have a method `get()` on the provider `private Optional getOptionalUser() {}` – Siddharth Prakash Singh Jul 19 '15 at 03:20
  • Not quite. Can you show your bean where you would want to return that? – Vaelyr Jul 19 '15 at 07:55
  • Added more context to the question. Please check the Post Edit section. – Siddharth Prakash Singh Jul 20 '15 at 05:14