美文网首页
使用注解配置Spring初始化bean时选用的构造器

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

作者: SmileMylife | 来源:发表于2019-10-16 14:50 被阅读0次

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

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

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

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

//以下是@autowired注解的官方解释
* <p>Only one constructor (at max) of any given bean class may declare this annotation
 * with the 'required' parameter set to {@code true}, indicating <i>the</i> constructor
 * to autowire when used as a Spring bean. If multiple <i>non-required</i> 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时选用的构造器

      本文链接:https://www.haomeiwen.com/subject/dmqumctx.html