alokraop
alokraop

Reputation: 867

How to use a spring profile bean in another bean with default profile?

I have a bean under the "dev" profile:

@Bean(name="internalDL")
public Map<Client, List<String>> internalDistributionLists() {
    Map<Client, List<String>> distributionLists = new HashMap<Client, List<String>>();
    distributionLists.put(Client.DL_NAME, Arrays.asList("[email protected]"));
    return distributionLists;
}

I need to use this bean in another bean:

@Autowired
@Qualifier("internalDL")
private Map<String, List<String>> internalMailingList;

@Bean(name="internalMailingDetails")
public Map<Client, MailingDetails> internalMailingDetails() {
    Map<Client, MailingDetails> internalMailingDetails = new HashMap<Client, MailingDetails>();

    MailingDetails details = new MailingDetails();

    details.setMailingList(internalMailingList.get(Client.DL_NAME));
    details.setTemplateSubject("someTemplate");
    details.setTemplateBody("someTemplate");
    internalMailingDetails.put(Client.DL_NAME, details);

    return internalMailingDetails;
}

Now the mailing template is the same for all environments so i haven't put it in a config that's marked with a particular profile.

I tried initializing the profile both by initializing the ApplicationContextInitializer<ConfigurableApplicationContext> class:

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    applicationContext.getEnvironment().setActiveProfiles("dev");
}

and by putting it as a context parameter:

<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>dev</param-value>
</context-param>

None of them seem to work though. It keeps throwing a bean not found exception.

org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.Map com.fmr.bpo.asyncprocessingframework.invocator.wiring.configuration.pojo.common.RootConfig.internalMailingList

Thanks for the help.

Upvotes: 0

Views: 605

Answers (1)

Lovababu Padala
Lovababu Padala

Reputation: 2477

@Autowired doesn't work for collection beans. Use @Resource instead of @Autowire

@Resource
private Map<String, List<String>> internalMailingList;

And refer beans-property-is-not-setting-from-utillist-object

If you are using Spring 4.x later have a look at spring-framework-4-0-and-java-generics

Upvotes: 2

Related Questions