@@ autowired导致空对象

问题描述 投票:0回答:1

我正在使用Spring Boot,在Controller中,我试图使用new运算符创建对象,并尝试打印其工作值。但是对于存储库,我使用了@Autowired但结果为null

@RestController
public class SignupController {
    //@Autowired
    UserService userservice =new UserService() ;

    @GetMapping("/Allusers")
    public ResponseEntity<List<User>> allUsers() {
        System.out.print(userservice+"\n");
        List<User> userlist = userservice.getAllUsers();
        if (userlist.isEmpty()) {

            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        return new ResponseEntity<>(userlist, HttpStatus.OK);
    }

这是我自动连接“ UserRepository userrepo;”的服务类;

public class UserService {
     @Autowired
    UserRepository userrepo;

    public List<User> getAllUsers() {
        List<User> userlist = new ArrayList<User>();
        System.out.println(userrepo);
        userrepo.findAll().forEach(users -> userlist.add(users));
        System.out.println("hii");
        return userlist;
    }
spring-boot annotations autowired
1个回答
0
投票

将@Service批注添加到UserService类,并将构造函数添加到同一类。如下图所示;

@Service
public class UserService {

    private final UserRepository userrepo;

    public UserService(UserRepository userRepository) {
        this.userrepo = userRepository;
    }

    public List<User> getAllUsers() {
        List<User> userlist = new ArrayList<User>();
        System.out.println(userrepo);
        userrepo.findAll().forEach(users -> userlist.add(users));
        System.out.println("hii");
        return userlist;
    }
}

如果要使用@Autowired批注,请确保使用@Service或@Controller或@Component批注UserRepository类。这是必需的,因为我们需要说对象类型是Spring托管的组件。

© www.soinside.com 2019 - 2024. All rights reserved.