使用注解配置Spring初始化bean时选用的构造器

Spring初始化bean的时候默认是使用无参构造器进行创建bean,如果需要使用有参构造器创建bean需要怎么做呢?

1.在使用xml配置文件时,只需要在bean中添加进去相应的属性即可。

2.如果要使用注解进行配置,可以使用@autowired注解,添加到需要使用的构造器上。

@Autowired
    public JedisUtil(JedisPool jedisPool) {
        JedisUtil.jedisPool = jedisPool;
    }

//以下是@autowired注解的官方解释
* 

Only one constructor (at max) of any given bean class may declare this annotation * with the 'required' parameter set to {@code true}, indicating the constructor * to autowire when used as a Spring bean. If multiple non-required constructors * declare the annotation, they will be considered as candidates for autowiring. * The constructor with the greatest number of dependencies that can be satisfied by * matching beans in the Spring container will be chosen. If none of the candidates * can be satisfied, then a primary/default constructor (if present) will be used. * If a class only declares a single constructor to begin with, it will always be used, * even if not annotated. An annotated constructor does not have to be public.

你可能感兴趣的:(使用注解配置Spring初始化bean时选用的构造器)