简体   繁体   中英

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; 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 
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. To inject Myservice type to another You should declare MyService as a interface instead:

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

After that, declare an implementation of this interface (again, use Spring DI to inject String type):

    class BarService() implements Myservice{
        String servicename;

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

        }

   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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