使用spring自动布线时如何传递构造函数参数?

sam*_*ers 5 java spring dependency-injection inversion-of-control autowired

我们的项目使用 spring DI/IoC,所以我使用自动装配来注入 bean。程序需要在实例化过程中将参数传递给对象。并且参数在运行时(而不是在编译时)是已知的。

如何在使用自动装配时实现这一点。示例代码如下。

界面- IMessage

package com.example.demo.services;

public interface IMessage {
        String message(String name);
}
Run Code Online (Sandbox Code Playgroud)

实现-
SayHelloService

package com.example.demo.services;

import org.springframework.stereotype.Service;

@Service
public class SayHelloService implements IMessage {

    String id;

    public SayHelloService(String id) {
        super();
        this.id = id;
    }

    @Override
    public String message(String name) {
        return "Hello Dear User - " + name + ". Greeter Id: " + id ;
    }
}
Run Code Online (Sandbox Code Playgroud)

主服务

package com.example.demo.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
public class MasterService implements IMessage  {

    String creationTime;

    MasterService() {
        System.out.println("ms... default constructor");
        creationTime = Long.toString(System.currentTimeMillis());
    }

    //classic java way of creating service
    IMessage sayHelloServiceClassicWay = new SayHelloService(creationTime);

    //how to achieve above using spring auto wiring. Below code does not exactly do same.
    @Autowired
    @Qualifier("sayHelloService")
    IMessage sayHelloServiceAutoWired;

    @Override
    public String message(String name) {
        return name.toString();
    }    
}
Run Code Online (Sandbox Code Playgroud)

现在在上面的程序中(在MasterService中)如何替换

IMessage sayHelloServiceClassicWay = new SayHelloService(creationTime);

与弹簧等效代码。

Evg*_*eev 0

它的工作方式不同,在 Spring 上下文中使用构造函数参数创建 SayHelloService,然后 Spring 将自动装配它。无 xml 配置示例:

class B1 {
    @Autowired
    B2 b2;
}

class B2 {
    B2(int i) {
    }
}

@Configuration
class Config {

    @Bean
    B1 b1() {
        return new B1();
    }

    @Bean
    B2 b2() {
        return new B2(1);
    }
}
Run Code Online (Sandbox Code Playgroud)

在此示例中,Spring 将自动装配 B2,该 B2 具有带有一个参数的构造函数