spring 自动扫描、注册的类是否可以定义构造函数

答案是肯定的。

方法如下:

@Service
public class SimpleMovieLister {

    private MovieFinder movieFinder;

    @Autowired
    public SimpleMovieLister(MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }

}

 

@Repository
public class JpaMovieFinder implements MovieFinder {
    // implementation elided for clarity
}

 

 SimpleMovieLister类会被spring扫描并注册到 ApplicationContext中。

要注意:1 构造函数用@Autowired 注解

           2 构造函数的参数如果需要其他对象,则参数对象也要是可以自动注入的。

 

posted on 2016-10-13 11:32  shuimx  阅读(211)  评论(0)    收藏  举报

导航