Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用@Component指定属性名称/值_Java_Spring_Components_Autowired - Fatal编程技术网

Java 使用@Component指定属性名称/值

Java 使用@Component指定属性名称/值,java,spring,components,autowired,Java,Spring,Components,Autowired,请回答这个基本问题 我曾经使用@Autowired注释,其中可以使用该类的键/值格式为属性(类变量)指定一个值 <bean id="class" class="a.b.c.Class" lazy-init="true"> <property name="var1" value="${var1}" /> </bean> 我将类更改为带有组件扫描选项的@Component,它不需要自动连接。现在如何添加属性变量 另外,我不想在写Junits时

请回答这个基本问题

我曾经使用@Autowired注释,其中可以使用该类的键/值格式为属性(类变量)指定一个值

<bean id="class" class="a.b.c.Class" lazy-init="true">
        <property name="var1" value="${var1}" />
</bean>

我将类更改为带有组件扫描选项的@Component,它不需要自动连接。现在如何添加属性变量

另外,我不想在写Junits时遇到麻烦


谢谢,

看看参考()中Spring的@Value注释

应加载以下属性:

<beans>
   <context:property-placeholder location="classpath:/com/acme/your.properties"/>
</beans>

如果您考虑的是属性文件中的属性,请签出并添加注释

@Component
@PropertySource("classpath:myProps.properties")
public class MyComponent {

    @Value("${some.property}")
    private String valueFromProperty;

    // You can also use environment
    @Autowired
    private Environment env;

    public void someMethod() {
        String prop = env.getProperty("some.property");
        MyBean bean = new MyBean();
        bean.setProp(prop);
        return bean;
    }
}

什么意思?如果您谈论的是单元测试,我不喜欢使用Spring来解决依赖关系,而只是“手工连接”之类的东西。但是,如果您使用的是Spring测试运行程序和正确的上下文配置,那么它应该可以工作。很抱歉删除了此注释。我的意思是,我们可以像对自动连线的注释那样直接注入值注释吗?
@Value
应该在创建bean时注入,所以我假设答案是肯定的。