如果在servlet.xml和Java config类中都将bean声明为@Bean,将在春季创建多个bean

时间:2018-12-03 14:42:22

标签: spring

我确实通过在servlet.xml中提供bean以及通过java配置来创建bean。

问题:由于spring默认情况下会创建单例bean。现在弹簧容器会发生什么?它是否创建了多个bean,如在输出中所示,您可以看到第二次初始化的哈希码更改与先前的不同。单例行为是否仍然存在?如果是的话,首先初始化的旧豆发生了什么事。

servlet.xml

 <context:component-scan base-package="com.main" />
        <mvc:annotation-driven />
        <bean id="protoTypeBean" class="com.main.lazyBeanTest.PrototypeEntity">

        </bean>

我的Java配置类:

AppConfig.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.main")
public class AppConfig {


    @Bean(name="Entity")
    @Lazy //@Lazy then you will see that Entity A is initialized only at context.getBean call.
    public LazyEntity getEntityA(){
        return new LazyEntity();
    }

    @Bean
    //@Scope(value="prototype")
    public PrototypeEntity prototypeEntity(){
        return new PrototypeEntity();
    }

}

Service.java

@Service
public class Services {

    /*@Autowired
    private EntityA entityA;*/
    private static int number = 0;
    @Autowired
    private ApplicationContext context;

    public Services(){
        System.out.println("Services inital number: "+number);
        System.out.println(this.hashCode());
        System.out.println("Services constructor");

    }

    @PostConstruct
    public void initialized(){
        LazyEntity entityA  = context.getBean(LazyEntity.class);
        entityA.call();
    }
}

Prototype.java

@Component
public class PrototypeEntity {

    private static int number = 0;
    public PrototypeEntity(){
        System.out.println("initial value: "+number);
        number = number+1;
        System.out.println(this.hashCode());
        System.out.println("Entity PrototypeEntity initialized");
    }

    public void call(){
        System.out.println("Final value:"+ number);
        System.out.println(" PrototypeEntity Called");
    }
}

运行上面的程序时,我得到以下输出:

initial value: 0
HashCode of Prototype: 21106999
Entity PrototypeEntity initialized
Services inital number: 0
HashCode of Service: 823108631
Services constructor
Entity A initialized
A Called


initial value: 1
HashCode of Prototype: 778323158
Entity PrototypeEntity initialized
Services inital number: 0
HashCode of Service: 729146178
Services constructor
Entity A initialized
A Called


initial value: 2
HashCode of Prototype: 1492163379
Entity PrototypeEntity initialized

0 个答案:

没有答案