Skip to content

Instantly share code, notes, and snippets.

@truongquoc
Last active October 17, 2023 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save truongquoc/d661565913a363fef37d55e7a77e63b1 to your computer and use it in GitHub Desktop.
Save truongquoc/d661565913a363fef37d55e7a77e63b1 to your computer and use it in GitHub Desktop.
Injection dependency
package com.example.demo.controller;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AuthController {
private final UserService userService;
public AuthController(UserService getUserService) {
this.userService = getUserService;
}
@GetMapping("/me")
public ResponseEntity getUserInfo() {
if (userService.isAuthenticated()) {
return ResponseEntity.ok("Returned user information");
}
return ResponseEntity.ok("Unauthorized");
}
}
public interface UserService {
Boolean isAuthenticated();
}
package com.example.demo.service;
import org.springframework.stereotype.Service;
//@Service
public class UserServiceImpl implements UserService {
@Override
public Boolean isAuthenticated() {
return true;
}
}
package com.example.demo.config;
import com.example.demo.service.UserService;
import com.example.demo.service.UserServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebConfiguration {
@Bean
public UserService getUserService() {
return new UserServiceImpl();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment