如何使用@Bean方法根据运行时参数提供不同的bean

时间:2013-05-30 14:11:53

标签: java spring

我正在尝试创建一个@Configuration工厂bean,它应该根据运行时参数创建其他(原型)bean。我想使用基于java的配置,但不知怎的,我无法使它工作。

以下是一个例子:

enum PetType{CAT,DOG;}

abstract class Pet {    
}

@Component
@Scope("prototype")
class Cat extends Pet{
}

@Component
@Scope("prototype")
class dog extends Pet{
}

@Configuration
public class PetFactory{    
    @Bean
    @Scope("prototype")
    public Pet pet(PetType type){
        if(type == CAT){
            return new Cat();
        }else
            return new Dog();
    }
}

petFactory.animal(PetType.CAT);

我检查了春季文档以及此处提出的所有相关问题,但我最终将向创建的bean提供运行时参数。我需要向工厂提供运行时参数,必须使用它们来创建不同的bean。

修改 似乎(目前)没有办法将@Bean注释方法的参数定义为 “运行”。 Spring假定方法参数将用作新bean的构造函数args,因此它尝试使用容器管理的bean来满足此依赖关系。

3 个答案:

答案 0 :(得分:2)

这似乎可以很好地利用Spring Profiles功能。在这里,您可以阅读Java configurations,此处了解XML Profiles

您的个人资料将定义Pet bean。然后你的工厂可以连接那个bean。

要修改您使用的配置文件,只需添加:-Dspring.profiles.active = dog或-Dspring.profiles.active = cat(或您为其命名的任何内容)。

答案 1 :(得分:1)

尝试使用@Configurable:

class Factory {

    Pet newPetOfType(PetType type) {
        switch (type) {
            case CAT: return new Cat();
            ...
        }
    }

    @Configurable
    private static class Cat extends Pet {
        @Autowired private Prop prop;
        ...
    }
}

答案 2 :(得分:0)

你可以 @Autowire 将你的PetFactory bean放入必需的bean中,并在运行时调用所需类型的 animal()方法,如下面的方法:

@Configuration    
public class AppConfiguration {

    @Bean
    @Scope("prototype")
    public Pet getPet(PetType type) {

        if(type == CAT){
            return new Cat();
        } else
            return new Dog();
    }

}

//...
// Then in required class
@Service
public class PetService {

    @Autowired
    private AppConfiguration configuration;

    //.....

    public Pet getPetByType(PetType type) {
        return configuration.getPet(type);
    }

}