@Primary

自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常。

有两个Ball和BallBall都实现了GrilsInterface接口,在PrimaryAnnotion类中通过@Autowired注入GrilsInterface接口的时候,必须在Ball和BallBall其中的一个通过@Primary注解,这样在@Autowired注入GrilsInterface接口的时候,能找到对应的实现类。

例子:

package springAnnotions;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import interfaces.GirlsInterface;

@Component
public class PrimaryAnnotion {
    @Autowired
    private GirlsInterface girlsInterface;

}

@Component
@Primary
class Ball implements GirlsInterface {
    @Override
    public String getGirlsName() {
        return "hello, I am ball";
    }
}

@Component
class BallBall implements GirlsInterface {
    @Override
    public String getGirlsName() {
        return "hello, I am ballball";
    }
}

@Lazy(true)

@Lazy用于指定该Bean是否取消预初始化,用于注解类,延迟初始化。被@Lazy注释的类在spring容器初始化的时候不会初始化成bean,当有其他类注入该bean的时候,才会去初始化被@Lazy注释的类。

@Lazy有true和false两个入参。true表示生效,false表示不生效。

12-27 16:22
查看更多