Unit 5 Oops With Java
Unit 5 Oops With Java
● Configuration:
java config: . C
4 onstructor
@Bean ● Autowires by matching the constructor parameters to beans in the
@Scope("application")
publicApplicationBeanapplicationBean(){ container. Constructor injection is generally recommended for
returnnewApplicationBean(); mandatory dependencies.
} ● Example:
.
6 eb Socket Scope
W MLConfiguration:
X
<b ean id="a" class="com.example.A"autowire="constructor"/>
● WebSocket scope is used for beans that are associated with a
<b
ean id="b"class="com.example.B"/>
WebSocket session. It's available only in a WebSocket-enabled
application. J avaConfiguration:
● Suitable for WebSocket-specific beans that maintain state across @Autowired
publicA( Bb){
WebSocket sessions. this.b
=b;
● Configuration: }
java config:
@Bean . A
5 utodetect (Deprecated)
@Scope("websocket")
publicWebSocketBeanwebSocketBean(){ ● Attempts to autowire using constructor first, and if no constructor
returnnewWebSocketBean(); is found, uses byType.
} ● Example: This mode is deprecated and should be avoidedin favor
of explicit autowiring modes.
f or more details: 5.15 Annotations in Spring
https://docs.spring.io/spring-framework/reference/core/beans/factory-scop ● nnotations in Spring provide metadata about the beans and their
A
es.html dependencies.
● They simplify configuration and reduce XML-based configuration.
5.14 Autowiring in Bean ● Usage: Used with components like @Component @Autowired
, ,
● A utowiring is Spring's feature that allows automatic dependency @Scope
@RequestMapping
, , etc.
injection. ● Example:
● It simplifies bean wiring by letting Spring resolve dependencies based
RestController
@
on type or name.
@RequestMapping("/api")
● We used the@Autowiredannotations for the autowiringthe bean publicclassMyController{
● Reduces boilerplate code and manual bean wiring.
Autowired
@
Autowired
@ privateMyServicemyService;
privateDependencydependency; }
● Types: ByType, ByName, Constructor, Autodetect, etc.
.
1 o Autowiring (default)
N 5.16 Lifecycle callbacks
● No automatic wiring is performed. Dependencies must be ● lifecycle callbacks are methods that allow you to hook into specific
manually injected. stages of a bean's lifecycle.
● Example: Default setting, no need for annotation orXML ● These stages include bean creation, initialization, and destruction.
configuration. ● The primary purpose of lifecycle callbacks is to provide a way to execute
custom logic during these stage :
.
2 ByType ● Application Started:Triggered right after the application starts.
● utowires by matching the type of the property to the type of a
A ● Spring Container Started:Triggered when the Spring IoC container
bean in the container. is initialized.
● Example:: ● Bean Constructed & Dependency Injection (DI): Beans are
MLConfiguration:
X instantiated and dependencies are injected.
<bean id="b" class="com.example.B"/> ● Custom Init Call:Custom initialization methods are called after the
<bean id="a" class="com.example.A"autowire="byType"/> bean is constructed.
J avaConfiguration:
● Other Methods Call:Regular business methods are invoked during
@Autowired the application's operation.
privateBb; ● Custom Destroy Call:Custom destruction methods are called
before the application shuts down.
.
3 yName
B
● Autowires by matching the name of the property to the name of a
bean in the container.
● Example:
MLConfiguration:
X
<bean id="a" class="com.example.A"autowire="byName"/>
<bean id="b" class="com.example.B"/>
J avaConfiguration:
@Autowired
privateBb;
5.17 Bean configuration MainApplication.java:
● B ean configuration in Spring refers to defining and managing beans ackagecom.e
p xample;
importorg.springframework.context.ApplicationContext;
within the Spring IoC (Inversion of Control) container. importorg.s pringframework.context.annotation.AnnotationConfigApplicationContext;
● There are several ways to configure beans in Spring: importorg.springframework.stereotype.Component;
● XML Configuration: Defining beans in XML files.
Component
@
● Annotation-Based Configuration: Using annotationsto define and publicclassDemoApplication{
configure beans. publicstaticvoidmain(S tring[]args){
ApplicationContextcontext=newAnnotationConfigApplicationContext("com.example");
● Java-Based Configuration: Using Java classes to configurebeans.
E xampleBeanexampleBean=context.getBean(ExampleBean.class);
exampleBean.display();
.
1 ML Configuration
X }
● Beans are defined in an XML file, typically named }
applicationContext.xml.
Configuration
@
ExampleBean.java: publicclassAppConfig{
ackagecom.example;
p
Bean
@
publicclassExampleBean{
publicExampleBeanexampleBean(){
privateStringpropertyName;
ExampleBeanbean=newExampleBean();
bean.setPropertyName("propertyValue");
publicvoidsetPropertyName(StringpropertyName){
returnbean;
this.propertyName=propertyName;
}
}
}
publicvoiddisplay(){
System.out.println("Property Value:"+propertyName); E xampleBean.java: Same as xml configuration file
} MainApplication.java:
} ackagecom.e
p xample;
importorg.springframework.context.ApplicationContext;
importorg.s pringframework.context.annotation.AnnotationConfigApplicationContext;
MainApplication.java:
ackagecom.example;
p publicclassDemoApplication{
importorg.springframework.c ontext.A pplicationContext; publicstaticvoidmain(S tring[]args){
ApplicationContextcontext=newAnnotationConfigApplicationContext(A
ppConfig.class);
importorg.springframework.c ontext.s upport.ClassPathXmlApplicationContext;
publicclassDemoApplication{ E xampleBeanexampleBean=context.getBean(ExampleBean.class);
publicstaticvoidmain(String[]args){ exampleBean.display();
ApplicationContextcontext=new }
ClassPathXmlApplicationContext("applicationContext.xml"); }
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.stereotype.Service;
Service
@
publicclassMyService{
privatestaticfinalLoggerlogger=LoggerFactory.getLogger(MyService.class);
publicvoiddoSomething(){
logger.trace("This is a TRACE message");
logger.debug("This is a DEBUG message");
logger.info("This is an INFO message");
logger.warn("This is a WARN message");
logger.error("This is an ERROR message");
}
}
SpringBootApplication
@
Explanation of Components publicclassDemoApplication{
publicstaticvoidmain(String[]args){
s rc/main/java:Contains the Java source code for your application.
● SpringApplication.r un(DemoApplication.c lass,args);
● com.example.myapplication:Root package structure. Replace }
com.example.myapplicationwith your actual package name. }
● MyApplication.java: Main class annotated with
S tep 3: Create a REST Controller
@SpringBootApplication, which serves as the entry point of the
● Create a controller to handle HTTP requests.
application.
UserController.java:
● controller: Package for Spring MVC controllers handling HTTP requests.
ackagecom.example.d
p emo.controller;
● service: Package for service classes containing business logic. importorg.springframework.web.bind.annotation.*;
● model: Package forPOJOclasses representing data entities. importjava.util.A rrayList;
● src/main/resources: Contains non-Java resources. importjava.util.L ist;
P
@ ostMapping DELETEhttp://localhost:8080/users/1 //delete the record id=1
publicUsercreateUser(@RequestBodyUseruser){
users.add(user);
returnuser; 5.23 @PathVariable
}
P
● urpose: Extract values from the URI path.
P
@ utMapping("/{id}") ● Usage: When values are part of the URL.
publicUserupdateUser(@PathVariableintid,@RequestBodyUserupdatedUser){
● Example: For URL /users/1, extract 1.
for(U seruser:users){
if(user.getId()==id){
GetMapping("/{id}")
@
user.setName(updatedUser.g etName());
publicStringgetUserById(@PathVariable("id")intuserId){
returnuser;
return"User ID:"+userId;
}
}
}
returnnull;
} 5.24 @RequestParam
P
● urpose: Extract query parameters from the URL.
D
@ eleteMapping("/{id}")
publicStringdeleteUser(@PathVariableintid){
● Usage: When values are passed as query parameters.
users.removeIf(user->user.g etId()==id); ● Example: For URL /users?page=2&size=10, extract page=2 and size=10
return"User with ID"+id+"deleted.";
} GetMapping
@
} publicStringgetUsers(@RequestParam("page")intpage,@R
equestParam("size")int
size){
return"Page:"+page+", Size:"+size;
S tep 4: Create a User Model }
● Define a User model class to represent user data.
User.java: 5.25 Using Both Together
packagecom.example.demo.controller;
P
● urpose: Capture values from both the path and query parameters.
publicclassUser{ ● Example: For URL /users/1/orders?page=1&size=5, extract userId=1,
privateintid; page=1, and size=5
privateStringname;
GetMapping("/{id}/orders")
@
ublicUser(){
p publicStringgetUserOrders(@PathVariable("id")intuserId,
} @RequestParam("page")intpage,
@RequestParam("size")intsize){
publicUser(intid,Stringname){ return"User ID:"+userId+", Page:"+page+", Size:"+size;
this.id=id; }
this.name=name;
}
5.26 GET API
publicintgetId(){ P
● urpose: Retrieve resources.
returnid; ● Example: Fetch user details.
} GetMapping("/{id}")
@
publicUsergetUserById(@PathVariable("id")intuserId){
publicvoidsetId(intid){ returnuserService.findUserById(u
serId);
this.id=id; }
}
5.27 POST API
publicStringgetName(){ P
● urpose: Create new resources.
returnname; ● Example: Add a new user.
}
PostMapping
@
publicUsercreateUser(@RequestBodyUseruser){
publicvoidsetName(Stringname){
returnuserService.saveUser(user);
this.name=name;
}
}
} 5.28 PUT API
P
● urpose: Update existing resources.
S tep 5: Running the Application ● Example: Update user details.
● Run the DemoApplication class. Your Spring Boot application will start, PutMapping("/{id}")
@
and the embedded Tomcat server will be launched. publicUserupdateUser(@PathVariable("id")intuserId,@RequestBodyUser
userDetails){
S tep 6: Testing Your RESTful Web Service returnuserService.updateUser(userId,userDetails);
}
● You can use tools like Postman or curl to test your RESTful web service.
5.29 DELETE API
● Examples:
P
● urpose: Delete resources.
GEThttp://localhost:8080/users // get all users ● Example: Remove a user.
DeleteMapping("/{id}")
@
GEThttp://localhost:8080/users/1 // get user id =1 publicResponseEntity<Void>deleteUser(@PathVariable("id")intuserId){
userService.d
eleteUser(userId);
OSThttp:/ /localhost:8080/users // store the record
P returnResponseEntity.noContent().build();
Body:{ }
"id":1,
5.30 REST Controller 5. Controller Class
● Handle web requests.
● Defines RESTful web services Controller
@
RestController
@ @RequestMapping("/users")
@RequestMapping("/api/users") publicclassUserController{
publicclassUserController{ @Autowired
@A utowired privateUserServiceuserService;
privateUserServiceuserService;
} GetMapping
@
publicStringgetAllUsers(Modelmodel){
model.addAttribute("users",userService.g etAllUsers());
5.31 Request Mapping return"user-list";
}
M
● aps HTTP requests to handler methods.
● Maps base URL for all endpoints. GetMapping("/{id}")
@
GetMapping
@ publicStringgetUserById(@PathVariable("id")Longid,Modelmodel){
publicList<U
ser>getAllUsers(){ model.addAttribute("user",userService.getUserById(id));
returnuserService.getAllUsers(); return"user-detail";
} }
GetMapping("/{id}")
@ GetMapping("/new")
@
publicUsergetUserById(@PathVariableLongid){ publicStringcreateUserForm(Modelmodel){
returnuserService.getUserById(id); model.addAttribute("user",newUser());
} return"user-form";
}
PostMapping
@
publicUsercreateUser(@RequestBodyUseruser){ PostMapping
@
returnuserService.saveUser(user); publicStringcreateUser(@ModelAttribute("user")Useruser){
} userService.s aveUser(user);
return"redirect:/users";
PutMapping("/{id}")
@ }
publicUserupdateUser(@PathVariableLongid,@RequestBodyUseruser){
user.setId(id); GetMapping("/edit/{id}")
@
returnuserService.saveUser(user); publicStringeditUserForm(@PathVariable("id")Longid,Modelmodel){
} model.addAttribute("user",userService.getUserById(id));
return"user-form";
DeleteMapping("/{id}")
@ }
publicvoiddeleteUser(@PathVariableLongid){
userService.deleteUser(id); PostMapping("/{id}")
@
} publicStringupdateUser(@PathVariable("id")Longid,@ModelAttribute("user")
Useruser){
user.s etId(id);
5.32 Request Body userService.s aveUser(user);
● Binds HTTP request body to a method parameter. return"redirect:/users";
PostMapping
@ }
publicUsercreateUser(@RequestBodyUseruser){
returnuserService.saveUser(user); GetMapping("/delete/{id}")
@
} publicStringdeleteUser(@PathVariable("id")Longid){
userService.d eleteUser(id);
return"redirect:/users";
5.33 Building Web Applications with Spring Boot }
1. Set Up Project }
● reate a Spring Boot project with dependencies:Spring Web,Thymeleaf,
C
Spring Data JPA.
2. Model Class . Thymeleaf Templates
6
● Define the entity. src/main/resources/templates/user-list.html:
Entity
@ < !DOCTYPEhtml>
publicclassUser{ <h tmlxmlns:th="http://www.thymeleaf.org">
@Id <h ead><title>User List</title></head>
@G eneratedValue(s trategy=GenerationType.IDENTITY) <b ody>
privateLongid; <h 1>User List</h1>
privateStringname; <a href="/users/new">Add New User</a>
privateStringemail; <t able>
// Getters and setters <tr><th>ID</th><th>Name</th><th>Email</th><th>Actions</th></tr>
} <trth:each="user : ${users}">
<tdth:text="${user.id}"></td>
<tdth:text="${user.name}"> </td>
3. Repository Interface
<tdth:text="${user.email}"></td>
● Interface for data access.
ublicinterfaceUserRepositoryextendsJpaRepository<User,Long>{
p
}
<td>
<ath:href="@{/users/{id}(id=${user.id})}">View</a>
5. Service Class <ath:href="@{/users/edit/{id}(id=${user.id})}">Edit</a>
● Handle business logic. <ath:href="@{/users/delete/{id}(id=${user.id})}">D elete</a>
Service
@ </td>
publicclassUserService{ </tr>
@A utowired </table>
privateUserRepositoryuserRepository; </body>
publicList<User>getAllUsers(){returnuserRepository.findAll();} </html>
publicUsergetUserById(L ongid){returnuserRepository.fi ndById(id).orElse(n
ull);}
publicUsersaveUser(Useruser){returnuserRepository.s ave(user);}
publicvoiddeleteUser(Longid){userRepository.d
eleteById(id);}
}
src/main/resources/templates/user-form.html:
< !DOCTYPEhtml>
<h tmlxmlns:th="http://www.thymeleaf.org">
<h ead><title>User Form</title></head>
<b ody>
<h 1>U ser Form</h1>
<f ormth:action="@{/users}"th:object="${user}"method="post">
<inputtype="hidden"th:field="*{id}">
<div><labelfor="name"> N ame:</label><inputtype="text"id="name"
th:field="*{name}"></div>
<div><labelfor="email"> E mail:</label><inputtype="text"id="email"
th:field="*{email}"></div>
<div><buttontype="submit">S ave</button></div>
</form>
<a href="/users"> Back to List</a>
</body>
</html>
src/main/resources/templates/user-detail.html:
< !DOCTYPEhtml>
<h tmlxmlns:th="http://www.thymeleaf.org">
<h ead><title>User Detail</title></head>
<b ody>
<h 1>U ser Detail</h1>
<p > ID:<spanth:text="${user.id}"> </span></p>
<p > Name:<spanth:text="${user.name}"> </span></p>
<p > Email:<s panth:text="${user.email}"></span></p>
<a href="/users"> Back to List</a>
</body>
</html>