Conteng Evolved

Stuff, mostly software development stuff

Optional Dependency for Method Parameter With Spring @Configuration

I started with a Spring Java configuration that looks like this:

1
2
3
4
5
6
@Configuration
public class MyConfig {
    MyService myService(Collection<RelatedService> relatedServices) {
        return new MyService(relatedServices);
    }
}

Basically Collection<RelatedService> is telling Spring to look for all beans matching the type of RelatedService and put them in a Collection for me to use in myService().

Then I wanted to make relatedServices an optional dependency. Ideally, I would like to be able to do something like this:

1
2
3
4
5
6
7
@Configuration
public class MyConfig {
    // invalid use of @Autowired
    MyService myService(@Autowired(required=false) Collection<RelatedService> relatedServices) {
        return new MyService(relatedServices);
    }
}

However, @Autowired cannot annotate a parameter. This is what I end up doing.

1
2
3
4
5
6
7
8
9
@Configuration
public class MyConfig {
    @Autowired(required=false)
    Collection<RelatedService> relatedServices

    MyService myService() {
        return new MyService(relatedServices);
    }
}

I would prefer to limit the visibility/scope of relatedServices within the method but it does not look possible.

Comments