Q.9. Write A Spring Program For Bean Scope Using Singleton ?
Q.9. Write A Spring Program For Bean Scope Using Singleton ?
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version> <!-- Choose the latest stable version -->
</dependency>
</dependencies>
gradle
dependencies {
implementation 'org.springframework:spring-context:5.3.25'
}
Step 2: Define the Bean Class
package com.example.spring;
public class MyBean {
private int counter = 0;
public MyBean() {
System.out.println("MyBean instance created");
}
public void incrementCounter() {
counter++; >> }
public int getCounter() { >> return counter;
} >> @Override
public String toString() {
return "MyBean [counter=" + counter + "]"; >> } >> }
Step 3: Define the Spring Configuration Class
package com.example.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean >> public MyBean myBean() {
return new MyBean(); >> } >> }
Step 4: Main Class to Run the Application
package com.example.spring;
import.org.springframework.context.annotation.AnnotationConfigAp
plicationContext;
public class Main {
public static void main(String[] args) {
// Create the Spring context using the configuration class
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
// Get two instances of the MyBean from the Spring container
MyBean bean1 = context.getBean(MyBean.class);
MyBean bean2 = context.getBean(MyBean.class);
// Demonstrate singleton behavior
System.out.println("Bean1 counter: " + bean1.getCounter());
System.out.println("Bean2 counter: " + bean2.getCounter());
// Increment counter of bean1 and check the counter for both beans
bean1.incrementCounter();
System.out.println("After incrementing counter for bean1:");
System.out.println("Bean1 counter: " + bean1.getCounter());
System.out.println("Bean2 counter: " + bean2.getCounter()); //
Since it's a singleton, both counters should be the same
// Close the context
context.close();
} >> }
Output :-
MyBean instance created
Bean1 counter: 0
Bean2 counter: 0
After incrementing counter for bean1:
Bean1 counter: 1
Bean2 counter: 1
Q.10. Write a spring program to implement bean life cycle by using
annotation ?
pom.xml >> <dependencies> >> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version> <!-- Use the latest version -->
</dependency> >> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.25</version> <!-- Use the latest version -->
</dependency>
<!-- Optional if using an embedded server like Tomcat -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.7.5</version>
</dependency> >> </dependencies>
MyBean.java (Bean with Lifecycle Methods):
package com.example.spring;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class MyBean {
// Constructor >> public MyBean() {
System.out.println("MyBean: Constructor called.");
} >> // Initialization method
@PostConstruct >> public void init() {
System.out.println("MyBean: @PostConstruct method called -
Bean is initialized.");
} >> // Destroy method
@PreDestroy >> public void destroy() {
System.out.println("MyBean: @PreDestroy method called - Bean
will be destroyed.");
} >> public void display() {
System.out.println("MyBean: display method called.");
} >> }
AppConfig.java (Configuration Class):
package com.example.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.example.spring")
public class AppConfig {
@Bean(initMethod = "init", destroyMethod = "destroy")
public MyBean myBean() { >> return new MyBean();
} >> }
Main.java:
package com.example.spring;
import.org.springframework.context.annotation.AnnotationConfigAp
plicationContext;
public class Main { >> public static void main(String[] args) {
// Create the Spring context using the AppConfig class
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
// Get the MyBean instance from the Spring container
MyBean myBean = context.getBean(MyBean.class);
// Call a method to see if the bean is working
myBean.display();
// Close the context (this will trigger the @PreDestroy method)
context.close();
} >> }
Output :-
MyBean: Constructor called.
MyBean: @PostConstruct method called - Bean is initialized.
MyBean: display method called.
MyBean: @PreDestroy method called - Bean will be destroyed.
Q.11. Write a spring program for dependency injection by using setter
with <property> tag.
MessageService.java (Service Bean)
package com.example.spring;
public class MessageService {
xsi:schemaLocation="http://www.springframework.org/schema/bea
ns
http://www.springframework.org/schema/beans/spring-
beans-4.3.xsd">
<!-- Define the MessageService Bean -->
<bean id="messageService"
class="com.example.spring.MessageService">
<property name="message" value="Hello, Spring DI with Setter
Injection!"/>
</bean>
<!-- Define the Client Bean, injecting MessageService via Setter
Injection -->
<bean id="client" class="com.example.spring.Client">
<property name="messageService" ref="messageService"/>
</bean>
Main.java
package com.example.spring;
import org.springframework.context.ApplicationContext;
import.org.springframework.context.support.ClassPathXmlApplicatio
nContext;
public class Main {
public static void main(String[] args) {
// Load the Spring context from XML configuration
ApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");
// Get the Client bean
Client client = context.getBean("client", Client.class);
// Call the method that uses the injected MessageService
client.showMessage();
}
}
Output :-
Message: Hello, Spring DI with Setter Injection!
Q.9. Create a spring MVC program using spring model interface
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.25</version> <!-- Choose the latest stable version -->
</dependency>
</dependencies>
gradle
dependencies {
implementation 'org.springframework:spring-context:5.3.25'
}
Step 2: Define the Bean Class
package com.example.spring;
public class MyBean {
private int counter = 0;
public MyBean() {
System.out.println("MyBean instance created"); >> }
public void incrementCounter() {
counter++; >> }
public int getCounter() {
return counter; >> }
@Override
public String toString() {
return "MyBean [counter=" + counter + "]"; >> } >> }
Step 3: Define the Spring Configuration Class
package com.example.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MyBean myBean() {
return new MyBean(); >> } >> }
Step 4: Main Class to Run the Application
package com.example.spring;
import.org.springframework.context.annotation.AnnotationConfigAp
plicationContext;
public class Main {
public static void main(String[] args) {
// Create the Spring context using the configuration class
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class);
// Get two instances of the MyBean from the Spring container
MyBean bean1 = context.getBean(MyBean.class);
MyBean bean2 = context.getBean(MyBean.class);
// Demonstrate singleton behavior
System.out.println("Bean1 counter: " + bean1.getCounter());
System.out.println("Bean2 counter: " + bean2.getCounter());
// Increment counter of bean1 and check the counter for both beans
bean1.incrementCounter();
System.out.println("After incrementing counter for bean1:");
System.out.println("Bean1 counter: " + bean1.getCounter());
System.out.println("Bean2 counter: " + bean2.getCounter()); //
Since it's a singleton, both counters should be the same
// Close the context
context.close();
}
}
Output :-
Welcome to Spring MVC!
Q.10. Write a spring MVC program for multiple view pages.
web.xml (located in WEB-INF):
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
<!-- Spring MVC Dispatcher Servlet --> >> <servlet>
<servlet-name>dispatcher</servlet-name> >> <servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<load-on-startup>1</load-on-startup> >> </servlet>
<!-- Dispatcher Servlet Mapping --> >> <servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern> >> </servlet-mapping>
</web-app> >> AppConfig.java
package com.example.springmvc.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
importorg.springframework.web.servlet.config.annotation.Enabl
eWebMvc;
import.org.springframework.web.servlet.config.annotation.ViewReso
lverRegistry;
import.org.springframework.web.servlet.config.annotation.Web
MvcConfigurer;
import.org.springframework.web.servlet.view.InternalResourceView
Resolver;
@Configuration >> @EnableWebMvc
@ComponentScan(basePackages = "com.example.springmvc")
public class AppConfig implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver viewResolver = new
InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/"); // Location of JSP files
viewResolver.setSuffix(".jsp"); // The suffix for JSP files
registry.viewResolver(viewResolver); >> } >> }
HomeController.java
package com.example.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller >> public class HomeController {
@GetMapping("/home")
public String homePage(Model model) {
model.addAttribute("message", "Welcome to the Home Page!");
return "home"; // home.jsp >> @GetMapping("/about")
public String aboutPage(Model model) {
model.addAttribute("message", "This is the About Page.");
return "about"; // about.jsp >> } >> @GetMapping("/contact")
public String contactPage(Model model) {
model.addAttribute("message", "Contact us at
[email protected].");
return "contact"; // contact.jsp >> } >> }
home.jsp (Located in /WEB-INF/views/):
<!DOCTYPE html> >> <html> >> <head>
<title>Home Page</title> >> </head>
<body> >> <h1>${message}</h1>
<p><a href="/about">Go to About Page</a></p>
<p><a href="/contact">Go to Contact Page</a></p>
</body> >> </html>
Main.java (Spring Boot Main Class):
package com.example.springmvc;
import org.springframework.boot.SpringApplication;
import.org.springframework.boot.autoconfigure.SpringBootAppl
ication; >> @SpringBootApplication
public class Main { >> public static void main(String[] args) {
SpringApplication.run(Main.class, args); >> } >>
}Output :- home Page: http://localhost:8080/home
About Page: http://localhost:8080/about
Contact Page: http://localhost:8080/contact
Q.11. Write a spring MVC program using ViewResolver.
pom.xml >> <dependencies>
<!-- Spring Web MVC --> >> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.25</version> <!-- Use latest version -->
</dependency> >> <!-- Spring Core -->
<dependency> >> <groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.25</version> >> </dependency>
<!-- Apache Tomcat (Embedded server, if using Spring Boot or
testing locally) --> >> <dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.50</version> >> </dependency>
<!-- JSP Dependency --> >> <dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version> >> <scope>provided</scope>
</dependency> >> </dependencies>
AppConfig.java (Spring Configuration)
package com.example.springmvc.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import.org.springframework.web.servlet.config.annotation.EnableW
ebMvc;
import.org.springframework.web.servlet.config.annotation.View
ResolverRegistry;
import.org.springframework.web.servlet.config.annotation.Web
MvcConfigurer;
import.org.springframework.web.servlet.view.InternalResource
ViewResolver;
@Configuration >> @EnableWebMvc
public class AppConfig implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver resolver = new
InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/"); // The folder where JSP
files are located
resolver.setSuffix(".jsp"); // The file extension of the views
registry.viewResolver(resolver); >> } >> }
HomeController.java (Controller)
package com.example.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller >> public class HomeController {
@GetMapping("/home") >> public String homePage(Model mode) {
model.addAttribute("message", "Welcome to Spring MVC with
ViewResolver!");
return "home"; // The view name (home.jsp will be resolved)
} >> }
web.xml (Deployment Descriptor)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!-- Spring DispatcherServlet --> >> <servlet>
<servlet-name>dispatcher</servlet-name> >> <servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<load-on-startup>1</load-on-startup> >> </servlet>
<!-- Dispatcher Servlet Mapping -->
<servlet-mapping> >> <servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern> >> </servlet-mapping>
</web-app>
Output :- <h1>Welcome to Spring MVC with ViewResolver!</h1>