问题
Using annotations; how do i pass arguments values to a method ?
Example in the below code "How can i pass arguments (2 strings) values for loadProperties API method" through annotations when Autowiring of confProps instance?I can use @javax.inject.Named at method argument level; but is there any equivalent for this in Spring to use at method argument level? I am not able to use @Component at the argument level.
Can i use these @Value("#{XXX}") OR @Qualifier("") to resolve my issue? These two are supported at method argument level.
Also please correct me if any other configuration mistakes i did it here.
@Configuration
Class Utilities {
@Bean(name = "loadProperties")
@Scope("prototype")
public static Properties loadProperties(String propsFileName, String type) throws Exception {
return Utilities.loadPropertiesFile(p_propsFileName);
}
}
@Service
@Scope(value = BeanDefinition.SCOPE_SINGLETON)
@Qualifier("strmContMgr")
public class StreamingControllerManager {
@Autowired
@Qualifier("loadProperties")
Properties confProps;
}
回答1:
Like any technology, Spring has it's taunts and limits. From your example, you have started to try to do everything (even the most simple things) using Spring. Looking at how you got there, that might make sense but you still ended up in a corner.
Or to put it another way: Just because you can doesn't mean it's smart to do.
Here is the solution for your problem:
@Configuration
Class StreamContollerConfig {
@Bean
public Properties streamControllerProperties() throws Exception {
return Utilities.loadPropertiesFile("some/fixed/name");
}
}
Try to avoid runtime "configurable" beans. They add a lot of complexity to your product with often little benefit.
Build your application from blocks with one final "configuration" block that wires and weaves everything together. That way, each block stays independent and simple.
回答2:
I dont know how this can be done through Annotation. For time being I am following XML way.
public class Utilities {
public static Properties loadProperties(String propsFileName, String type) throws Exception {
return Utilities.loadPropertiesFile(p_propsFileName);
}
}
@Service
@Scope(value = BeanDefinition.SCOPE_SINGLETON)
@Qualifier("strmContMgr")
public class StreamingControllerManager {
@Autowired
@Qualifier("loadProperties")
Properties confProps;
}
<beans>
<bean id="loadProperties" class="com.pactolus.Utilities"
factory-method="loadPropertiesFile">
<constructor-arg index="0" value="sc_beans.xml"/>
<constructor-arg index="1" value="CC"/>
</bean>
</beans>
来源:https://stackoverflow.com/questions/20210307/spring-annotations-how-to-create-autowire-annotation-for-static-non-static-meth