@Component("name") prototype singleton的理解

singleton:spring ioc容器中只会存在一个共享的bean实例,并且对所有语法,只要id与该bean定义相匹配,就可以返回bean的同一实例
prototype:对于每次getBean请求,都会创建一个新的Bean实例,相当于new
@Component("name"):相当于把普通pojo实例化到spring容器中

以下是实例

BeanTest.java

package tryBean;

import org.junit.Test;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service
//@Component("getBean")
@Configuration
public class BeanTest {
    
    public BeanTest() {
        
    }
    @Bean
    @Scope("prototype")
    public BeanTest getBean(){
        BeanTest bean = new  BeanTest();
        System.out.println("调用方法:"+bean);
        return bean;
    }
}

Main,java

package tryBean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
  
        ApplicationContext context = new AnnotationConfigApplicationContext(BeanTest.class);
        Object bean1 = context.getBean("getBean"); // wrong!
        System.out.println(bean1);
        Object bean2 = context.getBean("getBean");
        System.out.println(bean2);
        ((AbstractApplicationContext) context).close();
    }
}

运行结果:
调用方法:tryBean.BeanTest@7e9a5fbe
tryBean.BeanTest@7e9a5fbe
调用方法:tryBean.BeanTest@71623278
tryBean.BeanTest@71623278


那么如果把@scope("prototype")改变为@scope("singleton")结果会是什么呢?
运行结果:
调用方法:tryBean.BeanTest@47db50c5
tryBean.BeanTest@47db50c5
tryBean.BeanTest@47db50c5


如果@scope("prototype") 并且把@Component("getBean")的注释去掉呢?
运行结果:
tryBean.BeanTest$$EnhancerBySpringCGLIB$$cf0e9586@646007f4
tryBean.BeanTest$$EnhancerBySpringCGLIB$$cf0e9586@646007f4


如果@scope("singleton")并且把@Component("getBean")`的注释去掉呢?
运行结果:
tryBean.BeanTest$$EnhancerBySpringCGLIB$$cf0e9586@646007f4
tryBean.BeanTest$$EnhancerBySpringCGLIB$$cf0e9586@646007f4


可以看到:singleton会打印一次“调用方法”,而prototype会打印两次,说明singleton只有第一次创建了实例,而prototype两次都创建了实例。那么为什么加了@Component("getBean")之后就不再打印“调用方法”了呢?
原因是该注解将名为getBean的POJO实例化到spring容器中,从而每次实例化是无效的

你可能感兴趣的:(@Component("name") prototype singleton的理解)