Discuss / Java / validators放到user的构造函数里面...

validators放到user的构造函数里面...

Topic source

我想把validators放到user的构造函数里面,做了如下的改动

User这个class里面

@Component@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)public class User {    @Autowired    private Validators validators;
    public Validators getValidators()
    {
        return validators;
    }

以及

public User(long id, String email, String password, String name) {    this.id = id;    this.email = email;    this.password = password;    this.name = name;    getValidators().validate(this.email, this.email, this.name);}

错误是这样的:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService' defined in file [UserService.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.example.service.UserService]: Constructor threw exception; nested exception is java.lang.NullPointerException: Cannot invoke "org.example.service.Validators.validate(String, String, String)" because "this.validators" is null

就是在UserService里面这一部分调用new User出错了,因为在User里面的那个getValidators是空的

List<User> users = new ArrayList<>(List.of( // users:        new User(1, "bob@example.com", "password", "Bob"), // bob        new User(2, "alice@example.com", "password", "Alice"), // alice        new User(3, "tom@example.com", "password", "Tom"))); // tom

请问这是为什么呢?谢谢

廖雪峰

#2 Created at ... [Delete] [Delete and Lock User]

没事别用:

@Scope("prototype")

谢谢廖老师的回应。

这么说就是spring ioc还是适合用于Singleton的吗?

我后来琢磨了一下应该是因为user是new出来的就脱离了spring管理的范围。


  • 1

Reply