如何在spring的构造函数中注入特定的参数?

问题描述 投票:0回答:1
@Component
public class A {
    String one;
    int two;
    public A a = new ("bro",1);
    public A b = new ("come",2);

    public A(String one, int two) {
        this.one = one;
        this.two = two;
    }
}

我需要在类中创建 2 个对象。如何使用 Spring 的注释来做到这一点? 我应该在属性中指定任何值吗?我应该为 bean 创建创建一个配置类吗?

无法想出解决方案。请帮忙。

java spring dependency-injection annotations
1个回答
0
投票

只需创建不同的bean,它是同一个父类的子类,非常有必要为您阅读spring框架文档

这是代码片段

创建bean配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AConfig {

    @Bean
    public A a() {
        return new A("bro", 1);
    }

    @Bean
    public A b() {
        return new A("come", 2);
    }
}

用例

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SomeComponent {

    @Autowired
    private A a;

    @Autowired
    private A b;

    public void someMethod() {
        // Use instances of class A
        System.out.println(a.getOne()); // Output: bro
        System.out.println(a.getTwo()); // Output: 1
        System.out.println(b.getOne()); // Output: come
        System.out.println(b.getTwo()); // Output: 2
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.