简体   繁体   English

Spring Inject依赖于构造函数

[英]Spring inject dependency for constructors

I'm planning to create my objects in my Spring MVC using the below setup but How can I inject values to my MyService ie; 我打算使用以下设置在Spring MVC中创建对象,但是如何将值注入MyService中; instantiate the object with default value... 使用默认值实例化对象...

public class MyController {

    private MyService myService;


    @Autowired
    public void setMyService(MyService aService) { // autowired by Spring
        this.myService = aService;
    }

    @RequestMapping("/blah")
    public String someAction()
    {
        // do something here
        myService.foo();

        return "someView";
    }
}

MyService 我的服务

class Myservice(){
     String servicename;
     public Myservice(servicename){
           this.servicename = servicename;
     }

}

Without Spring 没有春天

  MyService first = new MyService("firstservice");
  MyService second = new MyService("secondservice");

Just declare your constructor with @Autowired to mark it as the constructor to use and its parameter with @Value to indicate the value to use. 只需使用@Autowired声明您的构造函数以@Autowired其标记为要使用的构造函数,并使用@Value参数@Value为指示要使用的值。

@Autowired 
public Myservice(@Value("example") String servicename){

Or use a placeholder 或使用占位符

@Autowired 
public Myservice(@Value("${placeholder.key}") String servicename){

Firstly, your exam are wrong on using Spring DI. 首先,您使用Spring DI的考试有误。 To inject Myservice type to another You should declare MyService as a interface instead: 要将Myservice类型注入另一个类型,您应该声明MyService作为接口:

interface Myservice(){         
    public void foo();
}

After that, declare an implementation of this interface (again, use Spring DI to inject String type): 之后,声明此接口的实现(再次,使用Spring DI注入String类型):

    class BarService() implements Myservice{
        String servicename;

        @Autowired
        public Myservice(@Value("servicename") String servicename){
             this.servicename = servicename;
        }
        public void foo(){

        }

   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM