java 如何使用@Named 注释从 Spring 3.0 中的属性注入构造函数参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4456214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 06:28:21  来源:igfitidea点击:

How to inject constructor parameters from properties in Spring 3.0 with the @Named annotation?

javaspringannotations

提问by binkley

I'm having trouble putting it all together:

我很难把它们放在一起:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">
    <context:property-placeholder location="classpath:some-useful.properties"/>
    <context:component-scan base-package="scan.me.scotty"/>
</beans>

Main is this:

主要是这个:

@Named
@Singleton
public class MySpringMain {
    @Inject
    public MySpringMain(final AReallyCool component) {
        component.runForAWhile();
    }

    public static void main(final String... args) {
        new ClassPathXmlApplicationContext(args);
    }
}

Component is this:

组件是这样的:

@Named
public class AReallyCool {
    @Inject
    public AReallyCool(@Named("whoAmI") final String whoAmI) {
        // do something here
    }
}

And properties is:

和属性是:

whoAmI=Who is anyone, really?

Naturally (for me) Spring dies the death:

自然地(对我来说)春天死了:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Named(value=whoAmI)}

Questions:

问题:

  • Is this even a reasonable approach?I'm trying to avoid Spring-specific annotations.
  • How would you make this work?
  • 这甚至是一种合理的方法吗?我试图避免特定于 Spring 的注释。
  • 你将如何使这项工作?

回答by Bill

A couple of Spring specific examples may help. As always the documentation at http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlis quite useful.

一些 Spring 特定示例可能会有所帮助。与往常一样,http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html 上的文档非常有用。

To read from a properties file look for the @Value annotation. Example:

要从属性文件中读取,请查找 @Value 注释。例子:

@Component
@Scope("prototype")
@ImportResource("classpath:spring/app-config.xml")
public class RancidService {

    private String filepath;
    private String filename;

    /**
     * Default constructor
     *
     * @param pathname
     */
    @Autowired
    public RancidService(@Value("#{ nccProperties['rancid.path']}") String filepath) {

        this.filepath = filepath;
    }

Here is an example of a main function @Autowired in

这是一个主函数@Autowired 的例子

@Component
public class GetCurrentMetric {


    /**
     * @param args
     */
    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring/app-config.xml");

        GetCurrentMetric p = context.getBean(GetCurrentMetric.class);
        p.start(args);

    }

    @Autowired
    private WhipService service;
    private void start(String[] args) {

        if (args.length != 2) {
            System.out.println("Usage: GetCurrentMetric <device> <interface>    Example: GetCurrentMetric cr1.lax1 p9/2");
        } else {
            String device = args[0];
            String iface = args[1];

            Map<String, String> map = service.getCurrentMetric(device, iface);

            if (map.size() == 2) {
                System.out.println("Level: " + map.get("level"));
                System.out.println("Metric: " + map.get("metric"));
            }
        }
    }

}

EDIT: Missed one important thing, for the properties file example at the top you'll need something in your application context file to tie it together. Example for above:

编辑:错过了一件重要的事情,对于顶部的属性文件示例,您需要在应用程序上下文文件中将其绑定在一起。上面的例子:

<!-- define the properties file to use --> 
<util:properties id="nccProperties" location="classpath:spring/ncc.properties" />