<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Sri </title>
    <description>The latest articles on DEV Community by Sri  (@s_srikamini_bfb9ce2df10).</description>
    <link>https://dev.to/s_srikamini_bfb9ce2df10</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3868750%2Fcf1f8f04-508b-4e05-9ac2-2e6cf7d82124.webp</url>
      <title>DEV Community: Sri </title>
      <link>https://dev.to/s_srikamini_bfb9ce2df10</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/s_srikamini_bfb9ce2df10"/>
    <language>en</language>
    <item>
      <title>Connecting to Redis cache and working with it</title>
      <dc:creator>Sri </dc:creator>
      <pubDate>Mon, 01 Jun 2026 02:07:24 +0000</pubDate>
      <link>https://dev.to/s_srikamini_bfb9ce2df10/connecting-to-redis-cache-and-working-with-it-2pm1</link>
      <guid>https://dev.to/s_srikamini_bfb9ce2df10/connecting-to-redis-cache-and-working-with-it-2pm1</guid>
      <description>&lt;ol&gt;
&lt;li&gt;Start Redis Server
Make sure Redis is running on the default port 6379.
Test it:
redis-cli ping
Expected:
PONG
________________________________________&lt;/li&gt;
&lt;li&gt;Add Dependency
For Maven:

org.springframework.boot
spring-boot-starter-data-redis

________________________________________&lt;/li&gt;
&lt;li&gt;Configure Redis
application.properties
spring.data.redis.host=localhost
spring.data.redis.port=6379
________________________________________&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Define a RedisTemplate Bean (Optional)&lt;br&gt;
@Configuration&lt;br&gt;
public class RedisConfig {&lt;/p&gt;

&lt;p&gt;&lt;a class="mentioned-user" href="https://dev.to/bean"&gt;@bean&lt;/a&gt;&lt;br&gt;
public RedisTemplate redisTemplate(&lt;br&gt;
        RedisConnectionFactory connectionFactory) {&lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;RedisTemplate&amp;lt;String, Object&amp;gt; template =
        new RedisTemplate&amp;lt;&amp;gt;();

template.setConnectionFactory(connectionFactory);
return template;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;}&lt;br&gt;
}&lt;/p&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Use RedisTemplate&lt;br&gt;
Store Data&lt;br&gt;
@Service&lt;br&gt;
public class RedisService {&lt;/p&gt;

&lt;p&gt;@Autowired&lt;br&gt;
private RedisTemplate redisTemplate;&lt;/p&gt;

&lt;p&gt;public void save(String key, String value) {&lt;br&gt;
    redisTemplate.opsForValue().set(key, value);&lt;br&gt;
}&lt;br&gt;
}&lt;br&gt;
Read Data&lt;br&gt;
public String get(String key) {&lt;br&gt;
return (String) redisTemplate.opsForValue().get(key);&lt;br&gt;
}&lt;br&gt;
Delete Data&lt;br&gt;
public void delete(String key) {&lt;br&gt;
redisTemplate.delete(key);&lt;br&gt;
}&lt;/p&gt;


&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Controller Example&lt;br&gt;
@RestController&lt;br&gt;
@RequestMapping("/redis")&lt;br&gt;
public class RedisController {&lt;/p&gt;

&lt;p&gt;@Autowired&lt;br&gt;
private RedisService redisService;&lt;/p&gt;

&lt;p&gt;@PostMapping("/{key}/{value}")&lt;br&gt;
public String save(&lt;br&gt;
        @PathVariable String key,&lt;br&gt;
        @PathVariable String value) {&lt;/p&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;redisService.save(key, value);
return "Saved";
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;@GetMapping("/{key}")&lt;br&gt;
public String get(@PathVariable String key) {&lt;br&gt;
    return redisService.get(key);&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;@DeleteMapping("/{key}")&lt;br&gt;
public String delete(@PathVariable String key) {&lt;br&gt;
    redisService.delete(key);&lt;br&gt;
    return "Deleted";&lt;br&gt;
}&lt;br&gt;
}&lt;/p&gt;


&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Caching with Redis&lt;br&gt;
Enable caching:&lt;br&gt;
@SpringBootApplication&lt;br&gt;
@EnableCaching&lt;br&gt;
public class Application {&lt;br&gt;
}&lt;br&gt;
Use cache annotations:&lt;br&gt;
@Cacheable("users")&lt;br&gt;
public User getUser(Long id) {&lt;br&gt;
return userRepository.findById(id).orElse(null);&lt;br&gt;
}&lt;br&gt;
@CacheEvict(value = "users", key = "#id")&lt;br&gt;
public void deleteUser(Long id) {&lt;br&gt;
userRepository.deleteById(id);&lt;br&gt;
}&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;execute Get URL in postman:&lt;br&gt;
&lt;a href="http://localhost:8080/book/getAllBookDetails" rel="noopener noreferrer"&gt;http://localhost:8080/book/getAllBookDetails&lt;/a&gt;&lt;br&gt;
output:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "id1": 6,
    "author": {
        "authorId": 1,
        "authorName": null,
        "contactNumber": null,
        "state": null
    },
    "name": "PHYTHON"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;]&lt;br&gt;
REDIS in command prompt:&lt;br&gt;
127.0.0.1:6379&amp;gt; keys *&lt;br&gt;
1) "Books::6"&lt;br&gt;
127.0.0.1:6379&amp;gt;&lt;/p&gt;

&lt;p&gt;Step 2:&lt;br&gt;
&lt;strong&gt;initialising delete method with&lt;/strong&gt;&lt;br&gt;
@CacheEvict(value = "Books", key = "#bookIDFromRequest")&lt;br&gt;
@DeleteMapping("/DeleteBookDetails/{bookIDFromRequest}")&lt;br&gt;
public ResponseEntity DeleteBookDetails(@PathVariable int bookIDFromRequest) {&lt;br&gt;
    log.info("entering DeleteBookDetails");&lt;br&gt;
    String upDateBookStatus= bookService.DeleteBookDetailsService(bookIDFromRequest);&lt;br&gt;
    log.info("upDateBookStatus "+upDateBookStatus);&lt;br&gt;
    ErrorTemplate error = new ErrorTemplate();&lt;br&gt;
    if(upDateBookStatus.equalsIgnoreCase("DeleteBook Failed")){&lt;br&gt;
     error.setStatusCode(200);&lt;br&gt;
     error.setMessage("book id not found");&lt;br&gt;
     return ResponseEntity.status(400).body("Book id not found");&lt;br&gt;
     }&lt;/p&gt;




&lt;p&gt;Common Startup Error&lt;br&gt;
If you see:&lt;br&gt;
Unable to connect to Redis&lt;br&gt;
Connection refused: localhost:&lt;br&gt;
Points to remember&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Entity class must implements Serializale interface so as to allow @cachale to serialise the response oject.&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>database</category>
      <category>java</category>
      <category>springboot</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Redis Installation on windows</title>
      <dc:creator>Sri </dc:creator>
      <pubDate>Mon, 01 Jun 2026 01:52:45 +0000</pubDate>
      <link>https://dev.to/s_srikamini_bfb9ce2df10/redis-installation-on-windows-234a</link>
      <guid>https://dev.to/s_srikamini_bfb9ce2df10/redis-installation-on-windows-234a</guid>
      <description>&lt;p&gt;Start server:&lt;/p&gt;

&lt;p&gt;Option 1: Run Command Prompt as Administrator&lt;br&gt;
Close the current Command Prompt.&lt;br&gt;
Open the Start menu.&lt;br&gt;
Search for cmd.&lt;br&gt;
Right-click Command Prompt → Run as administrator.&lt;br&gt;
Run&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;sc start redis&lt;/li&gt;
&lt;li&gt;&amp;gt;redis-cli.exe ping
expected output:
PONG&lt;/li&gt;
&lt;li&gt;redis-cli&lt;/li&gt;
&lt;li&gt;server with port no will be prompt in
keys *&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Shutdown server:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Redis-cli&lt;/li&gt;
&lt;li&gt;shutdown&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;delete keys &lt;br&gt;
1.type cmd Keys *&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;"Hello"&lt;/li&gt;
&lt;li&gt;"Sample"&lt;/li&gt;
&lt;li&gt;&lt;p&gt;"Books::6"&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;del Books::6&lt;br&gt;
output &lt;br&gt;
(integer 1)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;delete multiple keys&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;del Hello Sample&lt;br&gt;
(integer) 2&lt;/p&gt;

&lt;p&gt;Delete All Keys in Current Database&lt;br&gt;
FLUSHDB&lt;/p&gt;

&lt;p&gt;⚠️ This removes all keys from the currently selected Redis database.&lt;/p&gt;

&lt;p&gt;Delete All Keys in All Databases&lt;br&gt;
FLUSHALL&lt;/p&gt;

&lt;p&gt;⚠️ This removes everything from Red&lt;/p&gt;

</description>
      <category>start</category>
      <category>shutdown</category>
      <category>deletekeys</category>
      <category>in</category>
    </item>
    <item>
      <title>Rest Template - API for developers- Spring Boot</title>
      <dc:creator>Sri </dc:creator>
      <pubDate>Fri, 29 May 2026 12:38:53 +0000</pubDate>
      <link>https://dev.to/s_srikamini_bfb9ce2df10/rest-template-api-for-developers-spring-boot-1l</link>
      <guid>https://dev.to/s_srikamini_bfb9ce2df10/rest-template-api-for-developers-spring-boot-1l</guid>
      <description>&lt;p&gt;RestTemplate is a synchronous Spring Framework client used to consume RESTful web services by simplifying HTTP communication.&lt;br&gt;
Synchronous Communication: It blocks the execution thread until a response is received.HTTP Methods: It provides built-in methods for standard operations like GET, POST, PUT, and DELETE.Automatic Mapping: It can automatically convert JSON or XML responses into Java domain objects using message converters.Status: While widely used, it is in maintenance mode. For new projects, Spring recommends using the modern RestClient or the reactive.&lt;/p&gt;

&lt;p&gt;Its an automate work.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;getForObject()&lt;/strong&gt; Performs a GET request and returns the response body directly as an object.&lt;br&gt;
&lt;strong&gt;getForEntity()&lt;/strong&gt; Performs a GET request and returns a ResponseEntity (includes status and headers).&lt;br&gt;
&lt;strong&gt;postForObject()&lt;/strong&gt; Sends data via POST and returns the mapped response body.&lt;br&gt;
&lt;strong&gt;exchange()&lt;/strong&gt; A general-purpose method for all HTTP verbs, offering full control over headers and request entities.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;getForObject-&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Controller Snippet&lt;/strong&gt;&lt;br&gt;
Response is received in Object format.&lt;br&gt;
@RestController&lt;br&gt;
@RequestMapping("/api")&lt;br&gt;
public class ApiController {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Autowired
private ApiService apiService;

@GetMapping("/getUsers")
public String users() {
    return apiService.getUsers();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Service snippet:&lt;/strong&gt;&lt;br&gt;
@Service&lt;br&gt;
public class ApiService {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Autowired
private RestTemplate restTemplate;
@Autowired
UserApiRepo userApiRepo;
public String getUsers() {

    String url = "https://jsonplaceholder.typicode.com/users";

    String response = restTemplate.getForObject(url, String.class);

    return response;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Response:&lt;/strong&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
  "street": "Kulas Light",
  "suite": "Apt. 556",
  "city": "Gwenborough",
  "zipcode": "92998-3874",
  "geo": {
    "lat": "-37.3159",
    "lng": "81.1496"
  }
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
  "name": "Romaguera-Crona",
  "catchPhrase": "Multi-layered client-server neural-net",
  "bs": "harness real-time e-markets"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;getForEntity()&lt;/strong&gt;&lt;br&gt;
Response is received in ResponseEntity Format. It has Response Header,Response body an response.&lt;br&gt;
@GetMapping("/callGetEntityApi/{id}")&lt;br&gt;
    public String callApi(@PathVariable String id) {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    RestTemplate restTemplate = new RestTemplate();

    String url = "https://jsonplaceholder.typicode.com/posts/"+id;

    ResponseEntity&amp;lt;String&amp;gt; response =
            restTemplate.getForEntity(url, String.class);
   System.out.println("response.getStatusCode() " +response.getStatusCode() +"response.getHeaders() " +response.getHeaders());
    return response.getBody();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Output:&lt;/strong&gt;&lt;br&gt;
&lt;a href="http://localhost:8080/api/callGetEntityApi/1" rel="noopener noreferrer"&gt;http://localhost:8080/api/callGetEntityApi/1&lt;/a&gt;&lt;br&gt;
{&lt;br&gt;
  "userId": 1,&lt;br&gt;
  "id": 1,&lt;br&gt;
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",&lt;br&gt;
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;LogS:&lt;/strong&gt;&lt;br&gt;
2026-05-29T18:09:20.680+05:30 DEBUG 216 --- [LearningDemo] [nio-8080-exec-3] o.s.web.client.RestTemplate              : &lt;strong&gt;Response 200 OK&lt;/strong&gt;&lt;br&gt;
2026-05-29T18:09:20.682+05:30 DEBUG 216 --- [LearningDemo] [nio-8080-exec-3] o.s.web.client.RestTemplate              : Reading to [java.lang.String] as "application/json;charset=utf-8"&lt;br&gt;
2026-05-29T18:09:20.688+05:30 DEBUG 216 --- [LearningDemo] [nio-8080-exec-3]** m.m.a.RequestResponseBodyMethodProcessor : Using 'text/plain', given [&lt;em&gt;/&lt;/em&gt;] and supported [text/plain, &lt;em&gt;/&lt;/em&gt;, application/json, application/&lt;em&gt;+json]&lt;/em&gt;*&lt;br&gt;
2026-05-29T18:09:20.690+05:30 DEBUG 216 --- [LearningDemo] [nio-8080-exec-3] m.m.a.RequestResponseBodyMethodProcessor : &lt;strong&gt;Writing ["[  {    "id": 1,    "name": "Leanne Graham",    "username": "Bret",    "email": "&lt;a href="mailto:Sincere@april"&gt;Sincere@april&lt;/a&gt;. (truncated)..."]&lt;/strong&gt;&lt;br&gt;
2026&lt;/p&gt;

&lt;p&gt;** PostForOject-**&lt;br&gt;
Service:&lt;br&gt;
public String createPost(JSOnRequest jsOnRequest) {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    String url = "https://jsonplaceholder.typicode.com/posts";

    Map&amp;lt;String, Object&amp;gt; body = new HashMap&amp;lt;&amp;gt;();

    body.put("title",jsOnRequest.getTitle() );
    body.put("body", jsOnRequest.getBody());
    body.put("userId", jsOnRequest.getUserId());

    String response = restTemplate.postForObject(
            url,
            body,
            String.class
    );

    return response;
}
**Controller**
 @PostMapping("/postUsers")
public String postUsers(JSOnRequest request) {
    return apiService.createPost(request);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;**  Output**&lt;/p&gt;

&lt;p&gt;"title": "Java3",&lt;br&gt;
  "body": "Dell-Dark",&lt;br&gt;
  "userId": "4",&lt;br&gt;
  "id": 101&lt;/p&gt;

&lt;p&gt;headforheaders&lt;br&gt;
&lt;strong&gt;Service&lt;/strong&gt;&lt;br&gt;
 public MediaType getheadforheaders(){&lt;br&gt;
    String url = "&lt;a href="https://jsonplaceholder.typicode.com/users" rel="noopener noreferrer"&gt;https://jsonplaceholder.typicode.com/users&lt;/a&gt;";&lt;br&gt;
    HttpHeaders response = restTemplate.headForHeaders(url);&lt;br&gt;
    log.info(response.toString());&lt;br&gt;
    @Nullable MediaType responseList = response.getContentType();&lt;br&gt;
    return responseList;&lt;br&gt;
    }&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Controller&lt;/strong&gt;&lt;br&gt;
 @GetMapping("/getheadforheaders")&lt;br&gt;
    public MediaType headforheaders() {&lt;br&gt;
      return apiService.getheadforheaders();&lt;br&gt;
    }&lt;br&gt;
&lt;strong&gt;Output&lt;/strong&gt;&lt;br&gt;
{&lt;br&gt;
    "charset": "UTF-8",&lt;br&gt;
    "concrete": true,&lt;br&gt;
    "parameters": {&lt;br&gt;
        "charset": "utf-8"&lt;br&gt;
    },&lt;br&gt;
    "qualityValue": 1.0,&lt;br&gt;
    "subtype": "json",&lt;br&gt;
    "subtypeSuffix": null,&lt;br&gt;
    "type": "application",&lt;br&gt;
    "wildcardSubtype": false,&lt;br&gt;
    "wildcardType": false&lt;br&gt;
}&lt;br&gt;
&lt;strong&gt;delete&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;Service&lt;/strong&gt;&lt;br&gt;
public String getdeleteUser(Integer bookid){&lt;br&gt;
RestTemplate restTemplate = new RestTemplate();&lt;br&gt;
String url = "&lt;a href="http://localhost:8080/book/DeleteBookDetails/%7BbookId%7D" rel="noopener noreferrer"&gt;http://localhost:8080/book/DeleteBookDetails/{bookId}&lt;/a&gt;";&lt;br&gt;
restTemplate.delete(url,bookid);&lt;br&gt;
return "Success";&lt;br&gt;
}&lt;br&gt;
&lt;strong&gt;Controller&lt;/strong&gt;:&lt;br&gt;
    @GetMapping("/deleteUser/{id}")&lt;br&gt;
    public String deleteUser(@PathVariable Integer id) {&lt;br&gt;
        return apiService.getdeleteUser(id);&lt;br&gt;
    }&lt;br&gt;
&lt;a href="http://localhost:8080/api/deleteUser/3" rel="noopener noreferrer"&gt;http://localhost:8080/api/deleteUser/3&lt;/a&gt;&lt;br&gt;
output :: success&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PostForEntity&lt;/strong&gt;&lt;br&gt;
@PostMapping("/send")&lt;br&gt;
public String sendRequest(@RequestBody Laptop laptop) {&lt;br&gt;
  RestTemplate restTemplate = new RestTemplate();&lt;br&gt;
  String url = "&lt;a href="http://localhost:8080/Laptop/saveLaptop" rel="noopener noreferrer"&gt;http://localhost:8080/Laptop/saveLaptop&lt;/a&gt;";&lt;br&gt;
  log.info("laptop.getModelName()  "+laptop.getModelName()+"laptop.getLaptopModelId() " +laptop.getLaptopModelId()&lt;br&gt;
                +"laptop.getPrice() " +laptop.getPrice());&lt;br&gt;
  ResponseEntity response =restTemplate.postForEntity(&lt;br&gt;
                        url,&lt;br&gt;
                        laptop,&lt;br&gt;
                        String.class);&lt;br&gt;
  log.info(response.getStatusCode().toString());&lt;br&gt;
  return response.getBody();&lt;br&gt;
    }&lt;br&gt;
&lt;strong&gt;RestTemplate.exchange()&lt;/strong&gt; is the most flexible method in RestTemplate. It allows you to specify:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;HTTP method (GET, POST, PUT, DELETE, etc.)&lt;/li&gt;
&lt;li&gt;Request headers&lt;/li&gt;
&lt;li&gt;Request body&lt;/li&gt;
&lt;li&gt;Response type
&lt;strong&gt;Method Signature:&lt;/strong&gt;
ResponseEntity exchange(
String url,
HttpMethod method,
HttpEntity&amp;lt;?&amp;gt; requestEntity,
Class responseType
)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example&lt;/strong&gt; &lt;br&gt;
 @RequestMapping("/getExchange")&lt;br&gt;
public  ResponseEntity getExchange(HttpServletRequest request){&lt;br&gt;
    RestTemplate restTemplate = new RestTemplate(); // Initiate restTemplate&lt;br&gt;
    //Get BearerAuth from Heaer&lt;br&gt;
    String token=getBearertokenFromRequest(request);&lt;br&gt;
    log.info("token "+token);&lt;br&gt;
    HttpHeaders headers = new HttpHeaders();&lt;br&gt;
    headers.setBearerAuth(token);&lt;br&gt;
    //Perform Exchange Activity&lt;br&gt;
    HttpEntity entity = new HttpEntity&amp;lt;&amp;gt;(headers);&lt;br&gt;
    String URL="&lt;a href="http://localhost:8080/book/getBookDetailsForID/6" rel="noopener noreferrer"&gt;http://localhost:8080/book/getBookDetailsForID/6&lt;/a&gt;";&lt;br&gt;
    ResponseEntity response =&lt;br&gt;
            restTemplate.exchange(&lt;br&gt;
                    URL,&lt;br&gt;
                    HttpMethod.GET,&lt;br&gt;
                    entity,&lt;br&gt;
                    String.class&lt;br&gt;
            );&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;System.out.println(response.getBody());
return response;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
    public String getBearertokenFromRequest(HttpServletRequest request){&lt;br&gt;
        System.out.println("insie token");&lt;br&gt;
        String authHeader=request.getHeader("Authorization");&lt;br&gt;
        log.info("authHeader "+authHeader);&lt;br&gt;
        if(authHeader.startsWith("Bearer ")) {&lt;br&gt;
            return authHeader.substring(7);&lt;br&gt;
        }&lt;br&gt;
        return "Invalid Token";&lt;br&gt;
    }&lt;/p&gt;

&lt;p&gt;}&lt;/p&gt;

</description>
      <category>api</category>
      <category>backend</category>
      <category>java</category>
      <category>springboot</category>
    </item>
    <item>
      <title>Spring Security</title>
      <dc:creator>Sri </dc:creator>
      <pubDate>Tue, 19 May 2026 13:01:09 +0000</pubDate>
      <link>https://dev.to/s_srikamini_bfb9ce2df10/spring-security-4n7k</link>
      <guid>https://dev.to/s_srikamini_bfb9ce2df10/spring-security-4n7k</guid>
      <description>&lt;p&gt;Spring security provides authentication an authorisation.&lt;br&gt;
Spring Security is a security framework for Java and Spring Boot applications.&lt;/p&gt;

&lt;p&gt;It provides:&lt;/p&gt;

&lt;p&gt;Authentication → verifying user identity&lt;br&gt;
Authorization → controlling access&lt;br&gt;
Session management&lt;br&gt;
Password encryption&lt;br&gt;
CSRF protection&lt;br&gt;
JWT/OAuth2 support&lt;br&gt;
Spring security will be enabled after adding below XML defintions in POM.xml.&lt;/p&gt;

&lt;p&gt;&lt;br&gt;
org.springframework.boot&lt;br&gt;
spring-boot-starter-security&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;br&gt;
org.springframework.boot&lt;br&gt;
spring-boot-starter-security-test&lt;br&gt;
test&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;Spring security filters almost all pages except the pages which is marked to permit and gives login page.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Type 1:&lt;/strong&gt;&lt;br&gt;
Passwor will be automatically generate in devleoper tool console and user will be user.&lt;br&gt;
This password will be changedd on each application bootup.&lt;br&gt;
Flow :&lt;/p&gt;

&lt;p&gt;&lt;a href="http://localhost:8080/First/add/6/8" rel="noopener noreferrer"&gt;http://localhost:8080/First/add/6/8&lt;/a&gt;&lt;br&gt;
when the user clicks this link, instead of displaying output a login page will be shown, this is prewritten and plugged in using xml definition. the actual output of addition will be displayed after authentication.&lt;br&gt;
&lt;strong&gt;&lt;em&gt;Type:2&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
Adding our own username and password in application properties.&lt;br&gt;
spring.security.user.name=admin&lt;br&gt;
spring.security.user.password=generate&lt;br&gt;
Now application will not generate password but a login page will be shown on clicking the addition endpoint.&lt;br&gt;
User has to enter correct username and password mentioned in application.properties. After authenticating him, he will be redirected to the output page,else error with status code 403 will be displayed&lt;br&gt;
&lt;strong&gt;Type3:&lt;/strong&gt;&lt;br&gt;
Adding multiple users.&lt;br&gt;
we cannot add all users in property file. Though property file will not accept adding duplicate properties, in real time we will be having huge data  and adding in property or convincing it to accept is not an idea.&lt;/p&gt;

&lt;p&gt;So we can achieve this multiple user concept in spring security using UserDetailsManager Interface. Its implementation class is InMemoryUserDetailsManager.&lt;br&gt;
This accepts a list with userDetails objects.&lt;br&gt;
UserDetails is a static method with methods to add username,password,roles etc.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Here is the code snippet:&lt;/strong&gt;&lt;br&gt;
@Configuration&lt;br&gt;
@EnableWebSecurity&lt;br&gt;
public class SecurityConfig {&lt;br&gt;
&lt;a class="mentioned-user" href="https://dev.to/bean"&gt;@bean&lt;/a&gt;&lt;br&gt;
 public UserDetailsManager createUserDetailsManager(){&lt;/p&gt;

&lt;p&gt;UserDetails user1= User.withUsername("Sri").password("{noop}generate").roles("admin").build();&lt;br&gt;
UserDetails user2=User.withUsername("Desigan").password("{noop}generate").roles("user").build();&lt;br&gt;
        // Add users to the UserDetailsManager&lt;br&gt;
List l =   Arrays.asList(user1, user2);&lt;br&gt;
UserDetailsManager userDetailsManager = new InMemoryUserDetailsManager(l);&lt;br&gt;
return userDetailsManager;&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Authorisation:&lt;/strong&gt;&lt;br&gt;
It works based on user privilages.&lt;br&gt;
User with admin access can see all pages.&lt;br&gt;
User with read access can view pages but he cannot make any changes.&lt;br&gt;
we can set these privilages in security config class.&lt;/p&gt;

&lt;p&gt;&lt;a class="mentioned-user" href="https://dev.to/bean"&gt;@bean&lt;/a&gt;&lt;br&gt;
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    http
       // Disable CSRF (useful for REST APIs)
            .csrf(csrf -&amp;gt; csrf.disable())

       // Authorization rules
 .authorizeHttpRequests(auth -&amp;gt; auth
 .requestMatchers("/calc/add/**").permitAll()   // No auth required
 .requestMatchers("/calc/sub/**").hasRole("USER")
 .requestMatchers("/calc/mul/**").hasRole("ADMIN")
 .requestMatchers("/calc/div/**").hasRole("ADMIN")
 .anyRequest().authenticated()
            )
 .formLogin(Customizer.withDefaults());

    return http.build();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In above snippet ".permitAll()" allows the user to view endpoint without any authentication.&lt;br&gt;
For all the requestMatchers("/div/&lt;strong&gt;").hasRole("user") -&amp;gt; user with User role will be able to view this page.&lt;br&gt;
**Option 2: JDBCUserDetialsManager.&lt;/strong&gt;&lt;br&gt;
It is nothing but communicating with database to perform login.&lt;br&gt;
It has four steps, 1. collect data from UI 2. Request Database for UserDetails using loadByUserName(username) method from UserDetailService interface.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;compare data from UI with data from DB&lt;/li&gt;
&lt;li&gt;Provide success or failure login based on the results from above step.
To achieve this we need load data into DB first, This is what we call as "SIGNUP".
Im going to write an endpoint and send a request from POSTMan and load data into Database. This request again pass through Spring security firewall check. To allow our request to endpoint we can request spring security to permit our endpoint URL by adding below line.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;http.csrf(csrf -&amp;gt; csrf.disable())

            .authorizeHttpRequests(auth -&amp;gt; auth
             .requestMatchers("/", "/error").permitAll()
             .requestMatchers("/First/signUp/**").permitAll()
             .anyRequest().authenticated())
            .formLogin(Customizer.withDefaults());
           // .httpBasic(Customizer.withDefaults());

    return http.build();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Controller:&lt;/strong&gt;&lt;br&gt;
    @RequestMapping("/signUp")&lt;br&gt;
    ////@ResponseBody&lt;br&gt;
    public ResponseEntity processUserSignUp(@RequestBody User user ){&lt;br&gt;
        log.info("inside LearningFrontController.getmultiplyService");&lt;br&gt;
        response=calculatorService.processUserSignUp(user);&lt;br&gt;
        log.info(response);&lt;br&gt;
        if(response.equalsIgnoreCase("success")){&lt;br&gt;
            return ResponseEntity.status(200).body(response);&lt;br&gt;
        }&lt;br&gt;
        log.info("exiting LearningFrontController.getmultiplyService");&lt;br&gt;
        return ResponseEntity.status(400).body("Signup failed");&lt;br&gt;
    }&lt;br&gt;
&lt;strong&gt;Service:&lt;/strong&gt;&lt;br&gt;
 public String processUserSignUp(User user){&lt;br&gt;
       String response="failed";&lt;br&gt;
       UserDetailsEntity userDetailsEntity = new UserDetailsEntity();&lt;br&gt;
       userDetailsEntity.setUserName(user.getUserName());&lt;br&gt;
       String maskedPassword=passwordEncoder.encode(user.getPassword());&lt;br&gt;
       userDetailsEntity.setMaskedPassword(maskedPassword);&lt;br&gt;
       userDetailsEntity.setUserRole(user.getRoles());&lt;br&gt;
UserDetailsEntity userDetailsEntity1=   customUserDetailsRepo.save(userDetailsEntity);&lt;br&gt;
                if(userDetailsEntity1!=null) {&lt;br&gt;
                    return "success";&lt;br&gt;
                }&lt;br&gt;
            return response;&lt;br&gt;
        }&lt;br&gt;
JSON:&lt;/p&gt;

&lt;p&gt;{&lt;br&gt;
    "userName":"Sri",&lt;br&gt;
    "Password":"generate",&lt;br&gt;
    "roles":"User"&lt;br&gt;
}&lt;br&gt;
What we have in table?&lt;br&gt;
&lt;strong&gt;UserNo   PAssword                            userName        Role&lt;/strong&gt;&lt;br&gt;
202    $2a$10$PtbhgrteGOLk0azcyGK1x       SriKamini         USER&lt;br&gt;
203    $2a$10$WcefaBSrdqTIqLLOAh3XNep   Sri         USER&lt;br&gt;
&lt;strong&gt;Authenticate and Generate Token if authencation passes&lt;/strong&gt;&lt;br&gt;
Step 1. *&lt;em&gt;implement UserDetailsService Interface *&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;public class CustomUserDetailService implements UserDetailsService {&lt;br&gt;
    @Autowired&lt;br&gt;
    CustomUserDetailsRepo customUserDetailsRepo;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Optional&amp;lt;UserDetailsEntity&amp;gt; userDetailsEntityList = customUserDetailsRepo.findByUserName(username);

    if (userDetailsEntityList == null)
        return null;
    else {
        UserDetailsEntity userDetailsEntity = userDetailsEntityList.get();
        //convert userDetailsEntity to UserDetails
        UserDetails userDetails = User.withUsername(userDetailsEntity.getUserName())
                .password(userDetailsEntity.getMaskedPassword())
                .roles(userDetailsEntity.getUserRole()).build();
        return userDetails;

    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
Step2 IncluDe DAOAuthenticationProviDer in security Config&lt;br&gt;
Getting UserDetailsService in Below Snippet&lt;br&gt;
&lt;a class="mentioned-user" href="https://dev.to/bean"&gt;@bean&lt;/a&gt;&lt;br&gt;
    public UserDetailsService userDetailsService(){&lt;br&gt;
        return new CustomUserDetailService();&lt;br&gt;
    }&lt;br&gt;
   //Passing this generate CustomUserDetailService to DaoAuthenticationProvider &lt;br&gt;
    &lt;a class="mentioned-user" href="https://dev.to/bean"&gt;@bean&lt;/a&gt;&lt;br&gt;
    DaoAuthenticationProvider daoAuthenticationProvider(){&lt;br&gt;
          DaoAuthenticationProvider daoAuthenticationProvider&lt;br&gt;
           =new &lt;strong&gt;DaoAuthenticationProvider(userDetailsService());&lt;/strong&gt;&lt;br&gt;
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());&lt;br&gt;
        return daoAuthenticationProvider;&lt;br&gt;
    }&lt;/p&gt;

&lt;p&gt;//Creating an instance AuthenticationManager&lt;br&gt;
    &lt;a class="mentioned-user" href="https://dev.to/bean"&gt;@bean&lt;/a&gt;&lt;br&gt;
    public AuthenticationManager authenticationManager(&lt;br&gt;
            AuthenticationConfiguration config)&lt;br&gt;
            throws Exception {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    return config.getAuthenticationManager();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Step3&lt;br&gt;
Perform login from POSTMAN,&lt;br&gt;
This mentioneD Snippet will authenticate username &amp;amp; passwor coming in RequestBody.&lt;br&gt;
@PostMapping("/login")&lt;br&gt;
    public ResponseEntity&amp;lt;?&amp;gt; login(@RequestBody User request) {&lt;br&gt;
    log.info("inside login");&lt;br&gt;
    log.info("request.getUserName(), "+request.getUserName() + request.getPassword() + request.getPassword());&lt;br&gt;
        Authentication authentication = authenticationManager.authenticate(&lt;br&gt;
                new UsernamePasswordAuthenticationToken(&lt;br&gt;
                        request.getUserName(),&lt;br&gt;
                        request.getPassword()&lt;br&gt;
                )&lt;br&gt;
        );&lt;br&gt;
        String token = "";&lt;br&gt;
        log.info("authentication.isauthenticated"+authentication.isAuthenticated());&lt;br&gt;
        if(authentication.isAuthenticated()) {&lt;br&gt;
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();&lt;br&gt;
            token = jwtUtils.generateToken(String.valueOf(userDetails));&lt;br&gt;
        }&lt;br&gt;
        return ResponseEntity.ok(token);&lt;br&gt;
    }&lt;br&gt;
PostMan JSON&lt;br&gt;
{&lt;br&gt;
    "userName": "SriKamini",&lt;br&gt;
    "Password": "generate"&lt;br&gt;
}&lt;br&gt;
output:&lt;br&gt;
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJvcmcuc3ByaW5nZnJhbWV3b3JrLnNlY3VyaXR5LmNvcmUudXNlcmRldGFpbHMuVXNlciBbVXNlcm5hbWU9U3JpS2FtaW5pLCBQYXNzd29yZD1bUFJPVEVDVEVEXSwgRW5hYmxlZD10cnVlLCBBY2NvdW50Tm9uRXhwaXJlZD10cnVlLCBDcmVkZW50aWFsc05vbkV4cGlyZWQ9dHJ1ZSwgQWNjb3VudE5vbkxvY2tlZD10cnVlLCBHcmFudGVkIEF1dGhvcml0aWVzPVtST0xFX1VTRVJdXSIsImlhdCI6MTc3OTQ2ODEzNSwiZXhwIjoxNzc5NDY4NzM1fQ.EcUWMgOumkHi3Qo7Ggq7ju8FXqvrNob6_YSOm7WmbYs&lt;br&gt;
Login 2 &lt;strong&gt;Authorise the username &amp;amp; password coming in authorise tab in POSTMan. i.e credentials coming in authorise tab&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Login&lt;/em&gt;&lt;/strong&gt; :&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Rest Login using UserName an password in Request body&lt;/li&gt;
&lt;li&gt;Rest Login using UserName an password in Autorisation tab an request body can be anything &amp;amp; an it can be empty&lt;/li&gt;
&lt;li&gt;Rest Login using bearer token.&lt;/li&gt;
&lt;li&gt;Custom Login - Overrides default spring security login and it takes userdefined custom login.
 a.After custom Login redirect to home page
 b. After custom login redirect to the same endpoint which called custom login.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;_  Rest Login using UserName an password in Request body_&lt;/strong&gt;&lt;br&gt;
** Rest Login using UserName an password in Autorisation tab an request body can be anything &amp;amp; an it can be empty**&lt;br&gt;
Security config takes " .httpBasic(Customizer.withDefaults())"&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SecurityConfig.class:&lt;/strong&gt;&lt;br&gt;
&lt;a class="mentioned-user" href="https://dev.to/bean"&gt;@bean&lt;/a&gt;&lt;br&gt;
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {&lt;br&gt;
        .authorizeHttpRequests(auth -&amp;gt; auth&lt;br&gt;
        .requestMatchers("/", "/error").permitAll()&lt;br&gt;
        .anyRequest().authenticated())&lt;br&gt;
        .httpBasic(Customizer.withDefaults())&lt;br&gt;
        .addFilterBefore(&lt;br&gt;
           jwtAuthFilter,&lt;br&gt;
          UsernamePasswordAuthenticationFilter.class);&lt;br&gt;
 return http.build();&lt;br&gt;
    }&lt;br&gt;
&lt;strong&gt;AuthController.java&lt;/strong&gt;&lt;br&gt;
@RestController&lt;br&gt;
@RequestMapping("/api/1.0/security")&lt;/p&gt;

&lt;p&gt;public &lt;strong&gt;class AuthController&lt;/strong&gt; {&lt;br&gt;
private static final Logger log= LoggerFactory.getLogger(AuthController.class);&lt;br&gt;
@Autowired&lt;br&gt;
private  AuthenticationManager authenticationManager;&lt;br&gt;
@PostMapping("/perform_login")&lt;br&gt;
    public ResponseEntity&amp;lt;?&amp;gt; login(@RequestBody User request) {&lt;br&gt;
    log.info("inside login");&lt;br&gt;
    log.info("request.getUserName(), "+request.getUserName() +             request.getPassword() + request.getPassword());&lt;br&gt;
        Authentication authentication = authenticationManager.authenticate(&lt;br&gt;
                new UsernamePasswordAuthenticationToken(&lt;br&gt;
                        request.getUserName(),&lt;br&gt;
                        request.getPassword()&lt;br&gt;
                )&lt;br&gt;
        );&lt;br&gt;
        String token = "";&lt;br&gt;
        log.info("authentication.isauthenticated"+authentication.isAuthenticated());&lt;br&gt;
        if(authentication.isAuthenticated()) {&lt;br&gt;
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();&lt;br&gt;
            token = jwtUtils.generateToken(userDetails.getUsername());&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    }
    return ResponseEntity.ok(token);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;JWTUTil.java&lt;br&gt;
public String generateToken(String username) {&lt;br&gt;
                return Jwts.builder()&lt;br&gt;
                    .setSubject(username) // payload&lt;br&gt;
                    .setIssuedAt(new Date())&lt;br&gt;
                    .setExpiration(new Date(System.currentTimeMillis() +    1000 * 60 * 10)) // 10 mins&lt;br&gt;
                    .signWith(key)&lt;br&gt;
                    .compact();&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;2.**  Rest Login using UserName an password in Autorisation tab an request body can be anything &amp;amp; an it can be empty**&lt;br&gt;
If you enter username and password in authorisation tab, &lt;br&gt;
&lt;strong&gt;.httpBasic(Customizer.withDefaults())&lt;/strong&gt; will accept the input and handle the request.&lt;br&gt;
3.Rest Login using bearer token.&lt;br&gt;
JWT comes in picture to accept and validate this token.&lt;br&gt;
below  snippet is the controller code to accept the token and validate it.&lt;br&gt;
if jwt is enale in security config, JWT Auth filter handles this request an validates even Before it reaches controller&lt;/p&gt;

&lt;p&gt;@GetMapping("/token")&lt;br&gt;
public String token(HttpServletRequest request){&lt;br&gt;
System.out.println("insie token");&lt;br&gt;
String authHeader=request.getHeader("Authorization");&lt;br&gt;
log.info("authHeader "+authHeader);&lt;br&gt;
            if(authHeader.startsWith("Bearer ")) {&lt;br&gt;
                return authHeader.substring(7);&lt;br&gt;
            }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;        return "Invalid Token";
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;doFilterInternal() in JWTAuthFilter accepts all requests using "OncePerRequestFilter". If 1000 requests comes in then all these 1000 request must pass through this filter "OncePerRequestFilter "&lt;br&gt;
@Component&lt;br&gt;
public class JwtAuthFilter extends OncePerRequestFilter {&lt;br&gt;
&lt;a class="mentioned-user" href="https://dev.to/override"&gt;@override&lt;/a&gt;&lt;br&gt;
    protected void doFilterInternal(&lt;br&gt;
            HttpServletRequest request,&lt;br&gt;
            HttpServletResponse response,&lt;br&gt;
            FilterChain filterChain)&lt;br&gt;
            throws ServletException, IOException {&lt;br&gt;
        log.info("insife doFilterInternal");&lt;br&gt;
        String authHeader = request.getHeader("Authorization");&lt;br&gt;
        String token = null;&lt;br&gt;
        String username = null;&lt;br&gt;
        log.info("authHeader " + authHeader);&lt;br&gt;
       try{&lt;br&gt;
        try {&lt;br&gt;
            if (authHeader != null &amp;amp;&amp;amp; authHeader.startsWith("Bearer ")) {&lt;br&gt;
                token = authHeader.substring(7);&lt;br&gt;
                log.info("token " + token);&lt;br&gt;
                log.info(jwtUtils.toString());&lt;br&gt;
                username = jwtUtils.getUserName(token);&lt;br&gt;
                log.info("username " + username);&lt;br&gt;
            }} catch(Exception ex){&lt;br&gt;
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);&lt;br&gt;
                return;&lt;br&gt;
            }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    if (username != null &amp;amp;&amp;amp;
            SecurityContextHolder.getContext().getAuthentication() == null) {

        UserDetails userDetails =
                userDetailService.loadUserByUsername(username);
        log.info("value of valiate token " + jwtUtils.validateToken(token, userDetails));
        log.info("authorities "+userDetails.getAuthorities());
        if (jwtUtils.validateToken(token, userDetails)) {

            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(
                            userDetails,
                            null,
                            userDetails.getAuthorities()
                    );

            log.info("Credentials "+authentication.getCredentials());
            log.info("authorities " + userDetails.getAuthorities());
           // authentication.setDetails(userDetails);
            authentication.setDetails(
                    new WebAuthenticationDetailsSource()
                            .buildDetails(request)
            );

            SecurityContextHolder.getContext()
                    .setAuthentication(authentication);
        }
    }
    filterChain.doFilter(request, response);
}
catch(
Exception e) {
    e.printStackTrace();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Custom Login - Overrides default spring security login and it takes userdefined custom login.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;database connection object is achieved using&lt;br&gt;
declare this code in security connection class.&lt;br&gt;
 &lt;strong&gt;&lt;a class="mentioned-user" href="https://dev.to/bean"&gt;@bean&lt;/a&gt;&lt;/strong&gt;&lt;br&gt;
    public UserDetailsService userDetailsService(){&lt;br&gt;
        return new CustomUserDetailService(); &lt;br&gt;
    }&lt;br&gt;
    &lt;a class="mentioned-user" href="https://dev.to/bean"&gt;@bean&lt;/a&gt;&lt;br&gt;
    DaoAuthenticationProvider daoAuthenticationProvider(){&lt;br&gt;
        DaoAuthenticationProvider daoAuthenticationProvider=new    DaoAuthenticationProvider(userDetailsService());&lt;br&gt;
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());&lt;br&gt;
        return daoAuthenticationProvider;&lt;br&gt;
    }&lt;br&gt;
 &lt;a class="mentioned-user" href="https://dev.to/bean"&gt;@bean&lt;/a&gt;&lt;br&gt;
    public AuthenticationManager authenticationManager(&lt;br&gt;
            AuthenticationConfiguration config)&lt;br&gt;
            throws Exception {&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    return config.getAuthenticationManager();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;private final JwtAuthFilter jwtAuthFilter;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public SecurityConfig(JwtAuthFilter jwtAuthFilter) {
    this.jwtAuthFilter = jwtAuthFilter;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;security config also takes Below code &lt;br&gt;
.formLogin(form -&amp;gt; form&lt;br&gt;
                .loginPage("/api/1.0/security/login")&lt;br&gt;
                .loginProcessingUrl("/api/1.0/security/perform_login")&lt;br&gt;
               .defaultSuccessUrl("/First/index", true)&lt;br&gt;
                .failureUrl("/loginPage?error=true")&lt;br&gt;
                .permitAll())&lt;br&gt;
when defaultSuccessUrl is enaBled.after successful login, home page will be redirected.&lt;br&gt;
if we want to redirect to the enpoint which called the login service,&lt;br&gt;
step 1: &lt;a href="http://localhost:8080/First/add/6/8" rel="noopener noreferrer"&gt;http://localhost:8080/First/add/6/8&lt;/a&gt;&lt;br&gt;
Spring security custom login page will be displayed.&lt;br&gt;
after entering the credentials,".loginProcessingUrl("/api/1.0/security/perform_login")" will Be processed. JWTAuthFilter will happen and endpoint AuthController an its ,method with request mapping  "perform_login" will de called.  username authentication will happen here.&lt;br&gt;
Post Login,&lt;a href="http://localhost:8080/First/add/6/8" rel="noopener noreferrer"&gt;http://localhost:8080/First/add/6/8&lt;/a&gt;, Controller "First"with requestmapping"6 and 8 will be processed and output is displayed.&lt;/p&gt;

&lt;p&gt;Can we send RequestParams in POSTMAN?&lt;/p&gt;

&lt;p&gt;yes under the Body tab we have form_data tab.&lt;br&gt;
It takes key and value. we can send out requestparams in key as param name and value as its value to be processed.&lt;/p&gt;

</description>
      <category>backend</category>
      <category>java</category>
      <category>security</category>
      <category>springboot</category>
    </item>
    <item>
      <title>Spring Annotations Part2</title>
      <dc:creator>Sri </dc:creator>
      <pubDate>Thu, 16 Apr 2026 18:37:49 +0000</pubDate>
      <link>https://dev.to/s_srikamini_bfb9ce2df10/spring-annotations-part2-1aj5</link>
      <guid>https://dev.to/s_srikamini_bfb9ce2df10/spring-annotations-part2-1aj5</guid>
      <description>&lt;p&gt;&lt;strong&gt;@Restcontrolleradvice **&lt;br&gt;
A convenience annotation that combines @ControllerAdvice and @ResponseBody. It is designed for RESTful APIs where the return value of an exception handler is automatically serialized into the response body (typically as JSON or XML) instead of being resolved as a view.&lt;br&gt;
**@ExceptionHandler&lt;/strong&gt;&lt;br&gt;
We can use @ExceptionHandler to annotate methods that Spring automatically invokes when the given exception occurs. We can specify the exception either with the annotation or by declaring it as a method parameter, which allows us to read out details from the exception object to handle it correctly. The method itself is handled as a Controller method.&lt;br&gt;
EX:&lt;br&gt;
@RestControllerAdvice&lt;br&gt;
public class ExceptionController {&lt;br&gt;
    @ExceptionHandler(NullPointerException.class)&lt;br&gt;
     public String hanleNullPointerException(NullPointerException ex){&lt;br&gt;
         return "Error: "+ex.getMessage();&lt;br&gt;
     }&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@ExceptionHandler(MethodArgumentNotValidException.class)
public String hanleIllegalArgumentException(MethodArgumentNotValidException ex){
    return "Error: "+ex.getMessage();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;}&lt;br&gt;
&lt;strong&gt;&lt;a class="mentioned-user" href="https://dev.to/valid"&gt;@valid&lt;/a&gt;:&lt;/strong&gt;&lt;br&gt;
It informs controller about the presence of @ExceptionHandler.&lt;br&gt;
When an exception occurs,Spring container redirects the flow to corresponding Exception handler method&lt;br&gt;
@PostMapping("/SaveBookDetails")&lt;br&gt;
    public String SaveBookDetails(@RequestBody &lt;a class="mentioned-user" href="https://dev.to/valid"&gt;@valid&lt;/a&gt; BookDetails bookDetails) {&lt;br&gt;
        log.info("entering ProcessBookDetailsController");&lt;br&gt;
        String ValueFromService=bookService.SaveBookDetails(bookDetails);&lt;br&gt;
        log.info("leaving ProcessBookDetailsController");&lt;br&gt;
    return ValueFromService;&lt;br&gt;
    }&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;To Enable validations in coding we have Spring Boot validation dependency.&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;For Spring Boot applications,&lt;/strong&gt; the standard dependency for enabling Bean Validation is spring-boot-starter-validation. This starter provides the Jakarta Bean Validation API and Hibernate Validator as the default implementation. &lt;br&gt;
&lt;strong&gt;Enabling Validation&lt;/strong&gt;: Once the dependency is added, you must use annotations such as &lt;a class="mentioned-user" href="https://dev.to/valid"&gt;@valid&lt;/a&gt; or @Validated on your controller method parameters (e.g., @RequestBody) to trigger the validation process.&lt;br&gt;
Standard Annotations: The dependency supports standard JSR-380 annotations including @NotNull, &lt;a class="mentioned-user" href="https://dev.to/notblank"&gt;@notblank&lt;/a&gt;, @Size, &lt;a class="mentioned-user" href="https://dev.to/min"&gt;@min&lt;/a&gt;, &lt;a class="mentioned-user" href="https://dev.to/max"&gt;@max&lt;/a&gt;, and @Email.&lt;br&gt;
&lt;strong&gt;Historical Note&lt;/strong&gt;: Starting with Spring Boot 2.3, the validation starter is no longer included by default in spring-boot-starter-web or spring-boot-starter-webflux. You must add it explicitly to your project.&lt;br&gt;
Error Handling: When validation fails, Spring Boot typically throws a MethodArgumentNotValidException, which can be captured using a Global Exception Handler with @ControllerAdvice. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;pom.xml&lt;/strong&gt;&lt;br&gt;
Dependency Configurations&lt;br&gt;
&lt;br&gt;
org.springframework.boot&lt;br&gt;
spring-boot-starter-validation&lt;br&gt;
&lt;br&gt;
&lt;br&gt;
org.springframework.boot&lt;br&gt;
spring-boot-starter-validation-test&lt;br&gt;
test&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;Code:&lt;br&gt;
package LiBrary;&lt;/p&gt;

&lt;p&gt;import jakarta.validation.constraints.*;&lt;/p&gt;

&lt;p&gt;public class BookDetails {&lt;br&gt;
    @NotEmpty&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;String bookName;

@NotNull
@Positive
@Min(0)
@Max(50)
int bookId;
double price;

@NotBlank
@NotEmpty
String authorName;
String Genre;
@Email
String email;

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public double getPrice() {
    return price;
}

public void setPrice(double price) {
    this.price = price;
}

public String getBookName() {
    return bookName;
}

public void setBookName(String bookName) {
    this.bookName = bookName;
}

public int getBookId() {
    return bookId;
}

public void setBookId(int bookId) {
    this.bookId = bookId;
}

public String getGenre() {
    return Genre;
}

public void setGenre(String genre) {
    Genre = genre;
}

public String getAuthorName() {
    return authorName;
}

public void setAuthorName(String authorName) {
    this.authorName = authorName;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
Setting default error message for valid annotations:&lt;br&gt;
 @NotEmpty(message="bookname cannot be blank")&lt;br&gt;
    String bookName;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@NotNull(message="Book id cannot be null")
@Positive(message="Book Id must be +ve")
@Min(0)
@Max(50)
int bookId;
double price;

@NotBlank(message="author name cannot be blank")
@NotEmpty(message="author name cannot be empty")
String authorName;
String Genre;
@Email(message="Not a valid email address")
String email;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;error message:&lt;br&gt;
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [bookDetails.bookId,bookId]; arguments []; default message [bookId]]; default message [&lt;strong&gt;Book Id must be +ve&lt;/strong&gt;]] [Field error in object 'bookDetails' on field 'authorName': rejected value [ ]; codes [NotBlank.bookDetails.authorName,NotBlank.authorName,NotBlank.java.lang.String,NotBlank]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ResponseEntity:&lt;/strong&gt;&lt;br&gt;
ResponseEntity is a class in the Spring Framework used to represent the entire HTTP response. Unlike simply returning an object, it allows developers to fully configure the status code, headers, and response body sent back to the client. &lt;br&gt;
It can be any objectlike List, Map or user define class&lt;/p&gt;

&lt;p&gt;1.public class ResponseEntity extends HttpEntity&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Extension of HttpEntity that adds an HttpStatusCode status code. Used in RestTemplate as well as in @Controller methods.
3.In RestTemplate, this class is returned by getForEntity() and exchange():
&lt;strong&gt;Snippet 1:&lt;/strong&gt;
ResponseEntity entity = template.getForEntity("&lt;a href="https://example.com" rel="noopener noreferrer"&gt;https://example.com&lt;/a&gt;", String.class);
String body = entity.getBody();
MediaType contentType = entity.getHeaders().getContentType();
HttpStatus statusCode = entity.getStatusCode();
&lt;strong&gt;Snippet 2&lt;/strong&gt;
public ResponseEntity hanleIllegalArgumentException(MethodArgumentNotValidException ex){
    Map errors=new HashMap();
    //Code Snippet 1 - displays only key error message
    ex.getBindingResult().getFieldErrors().forEach(Error-&amp;gt;{
        errors.put(Error.getField(),Error.getDefaultMessage());
    });
    return new ResponseEntity("validation error "+errors , HttpStatusCode.valueOf(400));
    //Code Snippet 2 - displays all error with vast data
   // return new ResponseEntity("validation error "+ex.getMessage() , HttpStatusCode.valueOf(400));
}
output:
validation error {authorName=author name cannot be blank, bookName=bookname cannot be blank, email=Not a valid email address, bookId=must be less than or equal to 50}&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In above snippet we returned a map. we can also return a class &lt;br&gt;
&lt;strong&gt;References:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html" rel="noopener noreferrer"&gt;https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://dev.to/realnamehidden1_61/what-is-the-difference-between-controlleradvice-and-restcontrolleradvice-3jf3"&gt;https://dev.to/realnamehidden1_61/what-is-the-difference-between-controlleradvice-and-restcontrolleradvice-3jf3&lt;/a&gt;
3.&lt;a href="https://www.baeldung.com/exception-handling-for-rest-with-spring" rel="noopener noreferrer"&gt;https://www.baeldung.com/exception-handling-for-rest-with-spring&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>api</category>
      <category>backend</category>
      <category>java</category>
      <category>springboot</category>
    </item>
    <item>
      <title>SpringBoot Basic Annotations and Logging</title>
      <dc:creator>Sri </dc:creator>
      <pubDate>Thu, 09 Apr 2026 12:49:38 +0000</pubDate>
      <link>https://dev.to/s_srikamini_bfb9ce2df10/springboot-basic-annotations-and-logging-11ci</link>
      <guid>https://dev.to/s_srikamini_bfb9ce2df10/springboot-basic-annotations-and-logging-11ci</guid>
      <description>&lt;p&gt;Today we learned to create a spring project in Spring initializer.&lt;br&gt;
Here we learnt metadata is data about data, some of metadata in maven is artifact,groupid and version.&lt;br&gt;
we also learned about maven project structure and adding spring web dependency. Spring web gives tomcat automatically, whereas in eclipse we as a programmer explicitly add apache tomcat server and bring it up. spring web helps to withhold tomcat server and container takes care of bringing the server up. it helps developer to concentrate on business log instead of working in bringing the server up. Its a great feature of spring boot. &lt;/p&gt;

&lt;p&gt;Exploring logs:&lt;br&gt;
application.properties&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;server.port = 8080 //port in which localhost will be accessed&lt;/li&gt;
&lt;li&gt;logging.level.root=INFO //logger prints all abstract information into the console.&lt;/li&gt;
&lt;li&gt;logging.level.root=DEBUG // It prints all debug informations.errors.and INFO into the console.&lt;/li&gt;
&lt;li&gt;logging.level.root=TRACE// It prints fine-grained logic flow.
5.logging.level.com.spring.LearningDemo = DEBUG //If we want to print only our package logs, we can do it.
6.If we want to have a external logging file in local disk we use below code in application.properties.
logging.file.name = myapp.log
logging.file.path="/E:Spring projects/LearningDemo"&lt;/li&gt;
&lt;li&gt;In production we use logging.level.root=INFO to avoid unneccesary loggings. we use DEBUG only when we want identify a bug.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;context pat is  the base URL of app. here &lt;a href="http://localhost:8080/index" rel="noopener noreferrer"&gt;http://localhost:8080/index&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Annotations:&lt;br&gt;
@Controller &lt;br&gt;
Container idetifies the mentioned class as container using this annotation.&lt;/p&gt;

&lt;p&gt;@Controller&lt;br&gt;
public class LearningFrontController {&lt;br&gt;&lt;br&gt;
    public String getResponseFromLearningFrontController(){&lt;br&gt;
       return "Welcome to SpringBootFrontController";&lt;br&gt;
    }&lt;br&gt;
}&lt;br&gt;
In core Java programmer has to initialise an object to call any method from one class to another. whereas in spring and spring boot container takes of creating instances, programmer can concentrate on the business logic.&lt;br&gt;
A project can have any no of controllers, we can differentiate them using requestmapping annotaion.&lt;br&gt;
@Controller&lt;br&gt;
@RequestMapping("First")&lt;br&gt;
public class LearningFrontController {&lt;br&gt;
    private static final Logger log= LoggerFactory.getLogger(LearningFrontController.class);&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public String getResponseFromLearningFrontController(){
log.info("LearningFrontController started");
log.debug("Debug:LearningFrontController started");
log.debug("Debug:LearningFrontController completed");
return "Welcome to SpringBootFrontController";
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;similarly  a single container can have any no of methods so we exlplicitly differentiate the method using @RequestMapping("/add")&lt;/p&gt;

&lt;p&gt;@RequestMapping("/add/{a}/{b}")&lt;br&gt;
    @ResponseBody&lt;br&gt;
    public String   getAddResponseFromLearningFrontController(@PathVariable int a,@PathVariable int b){&lt;br&gt;
        log.info("LearningFrontController started");&lt;br&gt;
        log.debug("Debug:LearningFrontController started");&lt;br&gt;
        int c=a+b;&lt;br&gt;
        log.debug("Debug:LearningFrontController completed");&lt;br&gt;
        log.debug("Debug:LearningFrontController completed");&lt;br&gt;
        return "Addition is "+c;&lt;br&gt;
    }&lt;br&gt;
This method usually returns the view name and view resolver returns it to the client but when we want to return a value and inform the container to print the returned value as content of the page, we use "@ResponseBody" &lt;br&gt;
@RequestMapping("/Login/{username}/{password}")&lt;br&gt;
        //@ResponseBody&lt;br&gt;
        public String Login(@PathVariable String username,@PathVariable String password)&lt;br&gt;
        {&lt;br&gt;
            log.debug("Debug:welcomeUser started");&lt;br&gt;
            String name1 =username;&lt;br&gt;
            log.debug("Debug:welcomeUser completed");&lt;br&gt;
            return "welcome "+username;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;@RestController &lt;br&gt;
Combination of both Responsebody and controller.&lt;br&gt;
when all methods in the container uses response body, then we can mention one annotation at the top of the controller.&lt;br&gt;
@RestController&lt;br&gt;
@RequestMapping("/second")&lt;br&gt;
public class LearningFrontREquestController {&lt;br&gt;
        private static final Logger log= LoggerFactory.getLogger(com.learning.LearningDemo.LearningFrontController.class);&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public String getResponseFromLearningFrontController(){
        log.info("LearningFrontController started");
        log.debug("Debug:LearningFrontRequstController started");
        log.debug("Debug:LearningFrontrequstController completed");
        return "Welcome to SpringBootFrontController";
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Difference between Pathvariable and RequestPAram&lt;br&gt;
@PathVariable&lt;br&gt;
1.user is sending input to the method in URL.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Service will fetch this input from the url and handles in method when @Pathvariable is mentioned.&lt;/li&gt;
&lt;li&gt;URL format is http:/localhost::8080/firstControllerNameMappe/CallingMethoMap/{input1}/{input2}&lt;/li&gt;
&lt;li&gt;Its param are unique value like userid&lt;/li&gt;
&lt;li&gt;It can take only 20 arguments &amp;amp; It cannot take null values. if values are not sent in URL,it will throw 404 error.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;6.Using java.util.Optional: You can wrap the parameter in an Optional type (e.g., Optional id). If the path variable is missing from the URI, the value will be Optional.empty() rather than null.&lt;br&gt;
7.Handling with a Map: You can use a Map to capture all path variables. If a specific key is missing, its value in the map will be null.&lt;br&gt;
8.Using pathVariableOrNull (WebFlux): For applications using Spring WebFlux, the ServerRequest interface provides a pathVariableOrNull() helper method to handle missing variables gracefully.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;_@RequestParam&lt;br&gt;
_&lt;/strong&gt;1. Service will receive inputs from URL &amp;amp; URL is in below format&lt;br&gt;
   &lt;a href="http://localhost:8080/firstControllerNameMappe/CallingMethoMap?input1=6&amp;amp;input2=9" rel="noopener noreferrer"&gt;http://localhost:8080/firstControllerNameMappe/CallingMethoMap?input1=6&amp;amp;input2=9&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Request can have any no of arguments &amp;amp; it wont represent unique id&lt;/li&gt;
&lt;li&gt;it usually fetches a lengthy data ex:getting all the students name starting in K. It obviusly returns n no of  data &lt;/li&gt;
&lt;li&gt;It wont take empty arguments&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;@RequestBody&lt;br&gt;
when the input is in JSON format. we use RequestBody.&lt;br&gt;
JAckson library helps to convet JSON to object inside spring boot application and it also converts the object to JSON and send it back to POSTMAN.&lt;/p&gt;

&lt;p&gt;@RequestMapping("/divide")&lt;br&gt;
    //@ResponseBody&lt;br&gt;
    public Student getDivideService(@RequestBody Student student){&lt;br&gt;
        log.info("inside LearningFrontController.getSubtractService");&lt;br&gt;
        int a=student.getFirstValue();&lt;br&gt;
        int b=student.getSecondValue();&lt;br&gt;
        log.info("a "+a +"b "+b);&lt;br&gt;
        if((a!=0)&amp;amp;&amp;amp;(b!=0)) {&lt;br&gt;
            double divided = learningDemoService.divitionService(a, b);&lt;br&gt;
            student.setDivided(divided);&lt;br&gt;
        }&lt;br&gt;
        student.setName(student.getName().toUpperCase().trim());&lt;br&gt;
        log.info(response);&lt;br&gt;
        log.info("exiting LearningFrontController.getSubtractService");&lt;br&gt;
        return student;&lt;br&gt;
    }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;Object creation:&lt;br&gt;
In java:&lt;br&gt;
To have interaction between classes we will create object using new keyword.&lt;br&gt;
Student object=new Student();&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In Spring framework.&lt;/strong&gt;&lt;br&gt;
we will declare in XML&lt;/p&gt;

&lt;p&gt;In spring boot we have two annotations&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Component &lt;/li&gt;
&lt;li&gt;Bean 
&lt;strong&gt;Component:&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;It is declared in class level. If @Comparable is mentioned on top of class, An object will be create on compile time. &lt;/li&gt;
&lt;li&gt;Auto-detected via classpath scanning.&lt;/li&gt;
&lt;li&gt;Limited; uses Spring's default instantiation.&lt;/li&gt;
&lt;li&gt;Has specialized forms: @Service, @Repository, @Controller,@Configuration. &lt;/li&gt;
&lt;li&gt;@Component is an interface&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Bean:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It is declared in Method Level. It is declared in class which has @Configuration annotation on top of it.&lt;/li&gt;
&lt;li&gt;All classe with @Configuration annotation is loaded and all the methods,construtors are loaded and all objects mentioned in the constructors are created.&lt;/li&gt;
&lt;li&gt;It can be done in three ways setter injection, field injection, constructor injection. Field injection is not advisable.&lt;/li&gt;
&lt;li&gt;programmer can have full control over the class. &lt;/li&gt;
&lt;li&gt;we can create object for third party classes using Bean even library files. 
&lt;strong&gt;Snippet 1&lt;/strong&gt;
&lt;a class="mentioned-user" href="https://dev.to/bean"&gt;@bean&lt;/a&gt;(initMethod = "init", destroyMethod = "cleanup")
public MyService myService() {
return new MyService();
}
&lt;strong&gt;Ex&lt;/strong&gt;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;@Configuration&lt;br&gt;
public class Config {&lt;br&gt;
    private static final Logger log= LoggerFactory.getLogger(Config.class);&lt;br&gt;
    &lt;a class="mentioned-user" href="https://dev.to/bean"&gt;@bean&lt;/a&gt;&lt;br&gt;
    Student getStudent(){&lt;br&gt;
        log.info("inside student Bean creation config ");&lt;br&gt;
        return new Student();&lt;br&gt;
    }&lt;/p&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;How it works internally&lt;br&gt;
&lt;strong&gt;Application starts:&lt;/strong&gt;&lt;br&gt;
      SpringApplication.run(MyApp.class, args);&lt;br&gt;
&lt;strong&gt;Spring Boot:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Scans classes (@ComponentScan)&lt;/li&gt;
&lt;li&gt;    Reads config (@Configuration)&lt;/li&gt;
&lt;li&gt;     Applies auto-config (@EnableAutoConfiguration)&lt;/li&gt;
&lt;li&gt;      Beans are created and stored in:&lt;/li&gt;
&lt;li&gt;👉      ApplicationContext (Spring Container&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;@PostConstruct:&lt;/strong&gt;&lt;br&gt;
we use postconstruct when we want to add values to an object immediately after initialisation.&lt;br&gt;
&lt;strong&gt;&lt;em&gt;When it runs&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
After the bean is created and dependencies are injected&lt;br&gt;
✅ Purpose&lt;br&gt;
Initialization logic&lt;br&gt;
Setting default values&lt;br&gt;
Opening resources&lt;br&gt;
@PostConstruct&lt;br&gt;
    public void init(){&lt;br&gt;
        log.info("init method called");&lt;br&gt;
         studentFromBeanConfig.setName("Karthi");&lt;br&gt;
         studentFromBeanConfig.setLoginStatus(true);&lt;br&gt;
    }&lt;/p&gt;

&lt;p&gt;@PreDestroy&lt;br&gt;
It is used to delete values before destroying the same object.&lt;br&gt;
 @PreDestroy&lt;br&gt;
    public void preDestroy(){&lt;br&gt;
        System.out.println("Values are destroyed");&lt;br&gt;
    }&lt;br&gt;
Lifecycle of Bean :&lt;br&gt;
Bean Created → @PostConstruct → Bean in Use → @PreDestroy → Bean Destroyed&lt;/p&gt;

&lt;p&gt;Important Points for PreDestroy&lt;br&gt;
&lt;strong&gt;_Method must be:&lt;br&gt;
_&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;public&lt;/li&gt;
&lt;li&gt;void&lt;/li&gt;
&lt;li&gt;No arguments&lt;/li&gt;
&lt;li&gt;Works only for singleton beans by default&lt;/li&gt;
&lt;li&gt;Triggered when:
    Application stops
    Context is closed.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;&lt;a class="mentioned-user" href="https://dev.to/primary"&gt;@primary&lt;/a&gt; &amp;amp; @Qualifier&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
In Spring and Spring Boot, both &lt;a class="mentioned-user" href="https://dev.to/primary"&gt;@primary&lt;/a&gt; and @Qualifier are used to resolve autowiring ambiguity when multiple beans of the same type exist in the application context.&lt;br&gt;
&lt;strong&gt;Primary Annotation:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The &lt;a class="mentioned-user" href="https://dev.to/primary"&gt;@primary&lt;/a&gt; annotation in Spring is used to designate a primary bean among multiple beans of the same type. When a primary bean is defined using &lt;a class="mentioned-user" href="https://dev.to/primary"&gt;@primary&lt;/a&gt;, it is preferred for injection when no specific bean name or qualifier is provided.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;this is a class level annotation&lt;br&gt;
&lt;strong&gt;Qualifier Annotation:&lt;/strong&gt;&lt;br&gt;
On the other hand, the @Qualifier annotation is used to specify the exact bean to be injected when multiple beans of the same type are present. It works in conjunction with bean names or custom qualifiers to resolve ambiguity and specify the desired bean for injection.&lt;br&gt;
Example:&lt;br&gt;
@RestController&lt;br&gt;
@RequestMapping("student")&lt;br&gt;
public class StudentPrimaryAndQualiferService {&lt;br&gt;
@Autowired&lt;br&gt;
@Qualifier("JavaCoursestuent")&lt;br&gt;
StudentInterface studentInterface;&lt;/p&gt;

&lt;p&gt;@RequestMapping("/getStudentInferface")&lt;br&gt;
public String getStudentInterface(){&lt;br&gt;
    return "Name: "+studentInterface.getName()+ "Roll No :" +studentInterface.getRollNo();&lt;br&gt;
}&lt;br&gt;
}&lt;/p&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;package LearningBeanConfig;&lt;/p&gt;

&lt;p&gt;import org.springframework.context.annotation.Primary;&lt;br&gt;
import org.springframework.stereotype.Component;&lt;/p&gt;

&lt;p&gt;@Component&lt;br&gt;
&lt;a class="mentioned-user" href="https://dev.to/primary"&gt;@primary&lt;/a&gt;&lt;br&gt;
public class SchoolStudent implements StudentInterface{&lt;br&gt;
    &lt;a class="mentioned-user" href="https://dev.to/override"&gt;@override&lt;/a&gt;&lt;br&gt;
    public String getName() {&lt;br&gt;
        return "SchoolStudent";&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Override
public String getRollNo() {
    return "DAV-11";
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;package LearningBeanConfig;&lt;/p&gt;

&lt;p&gt;import com.Learning.LearningDemo.LearningDemoApplication;&lt;br&gt;
import org.slf4j.Logger;&lt;br&gt;
import org.slf4j.LoggerFactory;&lt;br&gt;
import org.springframework.stereotype.Component;&lt;/p&gt;

&lt;p&gt;@Component(value="JavaCoursestuent")&lt;br&gt;
public class JavaCourseStu implements StudentInterface {&lt;br&gt;
    private static final Logger log = LoggerFactory.getLogger(JavaCourseStu.class);&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Override
public String getName() {
    log.info("JavaCoursestuent.getNAme starts");
    return "Java Course StudentInterface ";
}

@Override
public String getRollNo() {
    log.info("JavaCoursestuent.getRollNo starts");
    return "RollNo1";
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

</description>
      <category>backend</category>
      <category>beginners</category>
      <category>java</category>
      <category>springboot</category>
    </item>
  </channel>
</rss>
