Issue
I am writing a small CRUD in Spring and Java. And I want to use a separate file for writing logic, this is very convenient for me, I did this when developing with NestJS. I have a few questions, is it correct to do this in Spring, or should I do everything inside a function in the controller. And if I write logic in a separate file, I should mark the logic class as @Component and the functions inside it as @Bean, right? I am new to Spring and as I understand it, I have to do this in order for the application to work correctly and my functions to be in the application context.
AuthLogic.java
@Component
public class AuthLogic {
@Bean
public void register() {
// code ...
}
}
AuthController.java
@RestController
public class AuthController {
@RequestMapping(value = "/register", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void register(@Valid @RequestBody UserDTO newUser) {
// here I call the register function from AuthLogic
}
}
Solution
You can write your business logic in a new separate file at service layer.
Suppose you name it as AuthService
and you mark it with annotation @Service.
@Service
public class AuthService{
}
You can then Autowire it in your controller class.
@RestController
public class AuthController {
@Autowired
AuthService authService;
@RequestMapping(value = "/register", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void register(@Valid @RequestBody UserDTO newUser) {
// here I call the register function from AuthLogic
}
}
Answered By - Drishti Jain
Answer Checked By - Cary Denson (JavaFixing Admin)