遇到的问题:
在springboot中,使用例如@Resource的spring容器依赖注入,那么在不同的controller中创建的对象,都具有相同的参数
@Resource
UserService userService;
同理,如果你在类中不使用 @Resource
、@Autowired
或其他类似的注解来注入Bean,而是通过手动创建对象的方式,你可以创建独立的实例。这些独立的实例将与通过Spring容器管理的Bean无关,拥有它们自己的参数和状态。这允许你在不同的类中拥有不同的实例,而不共享相同的Bean。
如果你希望在ArticleService
中拥有一个不同的 UserMapper
实例,你可以手动初始化它或者使用构造函数、Setter 方法等方式来注入一个不同的 UserMapper
实例。示例:
public class ArticleService {
private UserMapper articleMapper;
// 构造函数注入
public ArticleService(UserMapper articleMapper) {
this.articleMapper = articleMapper;
}
// 或者使用Setter方法注入
public void setArticleMapper(UserMapper articleMapper) {
this.articleMapper = articleMapper;
}
// ...
}
private UserMapper articleMapper = new UserMapper();也是可行的