0

我已将我的服务定义为:

@Component("myService")
public class MyServiceImpl implements MyService {
  public void serviceMethod(){
  }
}

我在我的客户端程序中使用此服务如下:

Public Class{
   @Autowired
   MyService myService;

   public void myMethod(){
     myService.serviceMethod();            
   }
}

但是,如果我在我的服务中有以下定义的构造函数:

@Component("myService")  
  public class MyServiceImpl implements MyService {
      private myVar;
      public MyServiceImpl(String myVar){
        this.myVar = myVar;
      }
      public void serviceMethod(){
      }
 } 

问题: 如何在我的客户端程序中自动装配,以便调用我定义的构造函数?

以下方法使用默认构造函数初始化对象:

 @Autowired
 MyService myService;
4

1 回答 1

0

It's not working that way...

Spring uses no-arg constructors to create beans and later it wires dependencies to those beans.

In your case Spring cannot know which String you want to pass to the constructor...

You can for example use java configuration to create your Service bean (and remove @Component from your bean)

@Configuration
public class Config {

    @Bean
    MyService myService() {
        return new MyService( "some string" );
    }

}
于 2013-02-19T07:02:31.420 回答