看到这个题目相信很多小伙伴都是懵懵的,平时我们的做法大都是下面的操作

 
@Component
public class People{

@Autowired
private Man man;
}
 

这里如果Man是单例的,这种写法是没有问题的,但如果Man是原型的,这样是否会存在问题。

错误实例演示

这里有一个原型(生命周期为prototype)的类

 
package com.example.myDemo.component;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope(value = "prototype")
public class Man  {

    public void eat() {
        System.out.println("I like beef");
    }
}
 

有一个单例(生命周期为singleton)的类

 
package com.example.myDemo.component;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Lookup;
import org.springframework.stereotype.Component;

@Component
public class Woman {
    //使用依赖注入的方式,注入原型的Man
@Autowired private Man man; public void eat() { System.out.println("man:"+man); System.out.println("I like fruits"); } }
 

下面看测试方法,

 
package com.example.myDemo;

import com.example.myDemo.component.MyFactoryBean;
import com.example.myDemo.component.Woman;
import com.example.myDemo.po.Student;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.context.ApplicationContext;

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class MyDemoApplication {

    public static void main(String[] args) {
        ApplicationContext ac=SpringApplication.run(MyDemoApplication.class, args);

        Woman woman=(Woman)ac.getBean("woman");
        for(int i=0;i<5;i++){
            woman.eat();
        }


    }

}
 

看下测试结果,

spring中如何向一个单例bean中注入非单例bean_java

上面的结果显示Woman中的man是单例的,因为5次循环打印打出的结果是同一个对象,发生了什么,