我假設你的字段(hastName,port,user和password)來自屬性文件,就像服務器配置一樣。
@Component
public class SomeClass {
@Autowired
public someclass(@Value("${server.hostName}") String hostName, @Value("${server.port}") int port, @Value("${server.user}") String user, @Value("${server.passowrd}") String password) {
this.user = user;
this.password = password;
}
}
如果你的參數不是靜態值,你可以使用編程方式。 在創建bean實例之前,您需要自動連接應用程序上下文。
@Autowired
private ApplicationContext ctx;
然後,創建你的bean實例並將其註冊到應用程序上下文,
BeanDefinitionRegistry registry = ((BeanDefinitionRegistry) ctx.getFactory());
GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
beanDefinition.setBeanClass(SomeClass.class);
beanDefinition.setLazyInit(false);
beanDefinition.setAbstract(false);
beanDefinition.setAutowireCandidate(true);
beanDefinition.setScope("singleton"); // you should deal your scope.
ConstructorArgumentValues constructor = beanDefinition.getConstructorArgumentValues();
constructor.addIndexedArgumentValue(0, hostName);
constructor.addIndexedArgumentValue(1, port);
constructor.addIndexedArgumentValue(3, user);
constructor.addIndexedArgumentValue(4, password);
String beanName = "someclass"; // give a name to your bean
BeanComponentDefinition definition = new BeanComponentDefinition(beanDefinition, beanName);
BeanDefinitionReaderUtils.registerBeanDefinition(definition, registry);
要小心,在處理你的bean範圍。您可以根據您的結構使用請求或會話範圍。
最後,您可以在其他類中自動裝配SomeClass;
@Autowired
public SomeClass someClass;
沒有。它不是來自屬性文件,因爲這與數據庫無關。所以,這些東西本質上是動態的,並且會從Java傳遞。 – Souvik
這意味着你不能在服務器啓動時創建這個spring bean。您不能使用組件掃描。因此,您應該在運行時創建此類的實例,並以編程方式將其註冊到Spring應用程序上下文。如果你願意,我可以提供更多的信息。但我相信你不能通過註釋來做到這一點。 – nsylmz
我認爲更多的信息對我非常有幫助。所以,根據評論唯一的選擇我是用「新」運營商手動做。 – Souvik