ssm

Spring中的Bean<3>

2017-08-10  本文已影响4人  天空在微笑
  1. 作用域:
 <bean name="user" class="com.lq.play.model.User" scope="singleton">
        <property name="id" value="32324324"/>
        <property name="username" value="singleton"/>
        <property name="password" value="singleton"/>
        <property name="salt" value="singleton"/>
    </bean>
    <bean name="user1" class="com.lq.play.model.User" scope="prototype">
        <property name="id" value="23443235"/>
        <property name="username" value="prototype"/>
        <property name="password" value="prototype"/>
        <property name="salt" value="prototype"/>
    </bean>

测试代码

   ApplicationContext applicationContext = new ClassPathXmlApplicationContext("config/spring/spring-servlet.xml");
        User user0 = applicationContext.getBean("user", User.class);
        System.out.println(user0);
        User user = applicationContext.getBean("user", User.class);
        System.out.println(user);
        User user1 = applicationContext.getBean("user1", User.class);
        System.out.println(user1);
        User user2 = applicationContext.getBean("user1", User.class);
        System.out.println(user2);
        System.out.println(user0==user);
        System.out.println(user1==user2);

输出结果

User{id=32324324, username='singleton', password='singleton', salt='singleton', locked=false}
User{id=32324324, username='singleton', password='singleton', salt='singleton', locked=false}
User{id=23443235, username='prototype', password='prototype', salt='prototype', locked=false}
User{id=23443235, username='prototype', password='prototype', salt='prototype', locked=false}
true
false
  1. bean的生命周期
    2.1 Spring提供了两种方式在bean全部属性设置成功后执行特定行为
void afterPropertiesSet() throws Exception;

注解使用@PostConstruct
2.2 Spring提供了两种方式在bean销毁之前的特定行为,

void destroy() throws Exception;

注解使用@PreDestroy

上一篇 下一篇

猜你喜欢

热点阅读