Service In Spring Boot For Beginners


Service in spring boot is component where you usually place your business logic of your application. So service will be the class where mostly you will write Java code. Business logic can be anything for example, when user update profile, buying items, checkout, etc.

So here's an example of simple service in spring for user registration, login, update, and remove.

@Service
public class UserService{

@UserRepository

private UserRepository userRepository;

public User registration(User newUser){
return userRepository.save(newUser);
}

public User login(UserDto user){
return userRepository.findByUsername(user.getUsername());
}

public User update(Long id, User newUser){
User user = userRepository.findById(id).orElse(new User);
user.setUsername(newUser.getUsername());

user.setName(newUser.getName());
userRepository.save(user);
return user;

}

public void remove(Long id){
userRepository.deleteById(id);
}
}

To make a class as a service, you add a @Service annotation, and on the above code we are auto wiring UserRepostiry which we already discuss on the previous post, please refer to:



And if there's something you need to know about spring, pleas leave a comment.

Comments

Popular posts from this blog

Flixify Video Streaming Platform

ASUS Battery Health Charging Software To Make Your Battery Life Longer

Push Notification Cordova, FCM And PHP