测试spring是单例模式

版权声明:欢迎转载 https://blog.csdn.net/weixin_33387378/article/details/87931253

spring默认为singleton,在scope中配置

package com.zpc.tet.SchedulTest;

/**
 * @Author timor
 * @Date 2019/2/26
 */
public class Apple {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
package com.zpc.tet.SchedulTest;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

/**
 * @Author timor
 * @Date 2019/2/26
 */
public class MyBean {
    @Bean(name = "getName")
    @Scope("prototype")
    public Apple getName(){
        Apple apple = new Apple();
        apple.setName("appleName");
        System.out.println("getName()");
        return apple;
    }
}
package com.zpc.tet.SchedulTest;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Date;

/**
 * @Author timor
 * @Date 2019/2/26
 */
@Configuration
public class BeanTest {


    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {

        ApplicationContext context = new AnnotationConfigApplicationContext(MyBean.class);
        Apple apple = (Apple) context.getBean("getName");
        Apple apple2 = (Apple) context.getBean("getName");
        System.out.println(apple == apple2);

        
    }
}

结果为:true

猜你喜欢

转载自blog.csdn.net/weixin_33387378/article/details/87931253