Spring中通过注解向构造函数注入参数 [英] Inject parameters to constructor through annotation in Spring

查看:124
本文介绍了Spring中通过注解向构造函数注入参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Spring Boot 注释配置.我有一个类的构造函数接受 2 个参数(字符串,另一个类).

I am using Spring Boot annotation configuration. I have a class whose constructor accepts 2 parameters (string, another class).

水果.java

public class Fruit {
    public Fruit(String FruitType, Apple apple) {
            this.FruitType = FruitType;
            this.apple = apple;
        }
}

Apple.java

public class Apple {

}

我有一个类需要通过向构造函数(iron Fruit",Apple 类)注入参数来自动装配上述类

I have a class that needs to autowire the above class by injecting parameters to the constructor("iron Fruit",Apple class)

Cook.java

public class Cook {

    @Autowired
    Fruit applefruit;
}

cook 类需要自动装配带参数的 Fruit 类(iron Fruit",Apple 类)

The cook class need to autowire Fruit class with parameters("iron Fruit",Apple class)

XML 配置如下所示:

The XML configuration looks like this:

<bean id="redapple" class="Apple" />
<bean id="greenapple" class="Apple" />
<bean name="appleCook" class="Cook">
          <constructor-arg index="0" value="iron Fruit"/>
          <constructor-arg index="1" ref="redapple"/>
</bean>
<bean name="appleCook2" class="Cook">
          <constructor-arg index="0" value="iron Fruit"/>
          <constructor-arg index="1" ref="greenapple"/>
</bean>

如何仅使用注解配置来实现?

How to achieve it using annotation configuration only?

推荐答案

Apple 必须是 spring-managed bean:

Apple must be a spring-managed bean:

@Component
public class Apple{

}

水果也是:

@Component
public class Fruit {

    @Autowired
    public Fruit(
        @Value("iron Fruit") String FruitType,
        Apple apple
        ) {
            this.FruitType = FruitType;
            this.apple = apple;
        }
}

注意 @Autowired@Value 注释的用法.

Note the usage of @Autowired and @Value annotations.

Cook 也应该有 @Component.

Cook should have @Component too.

更新

或者你可以使用 @Configuration@Bean 注释:

Or you could use @Configuration and @Bean annotations:

@Configuration 
public class Config {

    @Bean(name = "redapple")
    public Apple redApple() {
        return new Apple();
    }

    @Bean(name = "greeapple")
    public Apple greenApple() {
        retturn new Apple();
    }

    @Bean(name = "appleCook")
    public Cook appleCook() {
        return new Cook("iron Fruit", redApple());
    }
    ...
}

这篇关于Spring中通过注解向构造函数注入参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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