问答详情
源自:3-1 Spring Bean装配之Bean的配置项及作用域

若果需要应用作用域怎么办

若果需要应用作用域怎么办

提问者:_努力学习 2017-10-14 10:23

个回答

  • qq_凡曦_03855849
    2017-10-14 14:49:13

    //定义javaBean

    import org.springframework.context.annotation.Scope;

    import org.springframework.stereotype.Component;

    @Component

    @Scope("prototype")

    public class Person {

    private int id;

    private String name;

    public int getId() {

    return id;

    }

    public void setId(int id) {

    this.id = id;

    }

    public String getName() {

    return name;

    }

    public void setName(String name) {

    this.name = name;

    }

    }

    //测试类

    import org.springframework.context.ApplicationContext;

    import org.springframework.context.support.ClassPathXmlApplicationContext;


    /**

     * Hello world!

     *

     */

    public class App 

    {

        public static void main( String[] args )

        {

            ApplicationContext appContext = new ClassPathXmlApplicationContext("/spring.xml");

            Person p1 = appContext.getBean(Person.class);

            System.out.println("p1's identityHashCode is " + System.identityHashCode(p1));

            

            Person p2 = appContext.getBean(Person.class);

            System.out.println("p2's identityHashCode is " + System.identityHashCode(p2));

            

        }

    }

    @Scope("")类型不同,作用域范围不同