Spring Annotations:如何为带参数的静态/非静态方法创建自动装配注释 [英] Spring Annotations: How to create autowire annotation for static/non static method with arguments

查看:26
本文介绍了Spring Annotations:如何为带参数的静态/非静态方法创建自动装配注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 使用注解;我如何将参数值传递给方法?
    下面代码中的示例我如何在 confProps 实例的自动装配时通过注释传递 ​​loadProperties API 方法的参数(2 个字符串)值"?

  1. 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?

我可以在方法参数级别使用@javax.inject.Named;但是在 Spring 中是否有任何等价物可以在方法参数级别使用?我无法在参数级别使用 @Component.

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.

我可以使用这些@Value("#{XXX}") 或@Qualifier("") 来解决我的问题吗?这两个在方法参数级别受支持.

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;
}

推荐答案

像任何技术一样,Spring 也有它的嘲讽和限制.从您的示例中,您已经开始尝试使用 Spring 完成所有事情(即使是最简单的事情).看看你是如何到达那里的,这可能是有道理的,但你最终还是被困在了角落里.

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");
    }
}

尽量避免运行时可配置"bean.它们给您的产品增加了很多复杂性,但通常没有什么好处.

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.

这篇关于Spring Annotations:如何为带参数的静态/非静态方法创建自动装配注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆