@Scope("prototype")创建的对象为什么会一样?

本文通过实验对比了在Spring框架中使用@Scope注解与XML配置实现原型作用域的差异。实验表明,对于同一作用域定义,注解方式创建的对象实例在每次请求时都是新的,而XML方式则可能因为ApplicationContext的特性导致对象实例共享。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用Annotation的@Scope("prototype")实验两个对象还是相等的,用xml的scope="prototype"就不一样,代码如下:

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

import com.dao.UserDAO;
import com.model.User;

@Scope("prototype")
@Component("u")

public class UserDAOImpl implements UserDAO {

@Override
public void save(User u) {
System.out.println("a user saved");

}

}

 

public class UserServiceTest {

@Test
public void testAdd() throws Exception {


ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");//destroy在ApplicationContext没有要用具体的类来引用

UserService service = (UserService)ctx.getBean("userService");
UserService service2 = (UserService)ctx.getBean("userService");
System.out.println(service==service2);

service.add(new User());
ctx.destroy();

}

}

 

转载于:https://www.cnblogs.com/chuansao/p/4067381.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值