Remove all <bean>
tags from the XML configuration file.
Enable Annotation Support:
Add the context
namespace and the following tag in the XML configuration:
<context:annotation-config/>
@Autowired
, @PostConstruct
, @PreDestroy
, etc.).Add the following to enable beans and context namespace:
<beans xmlns="<http://www.springframework.org/schema/beans>"
xmlns:xsi="<http://www.w3.org/2001/XMLSchema-instance>"
xmlns:context="<http://www.springframework.org/schema/context>"
xsi:schemaLocation="<http://www.springframework.org/schema/beans> <http://www.springframework.org/schema/beans/spring-beans.xsd>
<http://www.springframework.org/schema/context> <http://www.springframework.org/schema/context/spring-context.xsd>">
Specify Base Package for Spring Beans:
Use:
<context:component-scan base-package="comma separated list of pkgs to specify spring beans"/>
Purpose: Specifies base package(s) for scanning Spring beans.
Behavior: SC scans the specified packages (including sub-packages) for classes annotated with stereotype annotations:
@Component
, @Service
, @Repository
, @Controller
, @RestController
, @ControllerAdvice
, etc.@Component
: Spring-managed bean class, without specific logic.@Controller
: For request-handling beans in Spring Web MVC.@Service
: For service layer (Business Logic) beans.@Repository
: For DAO layer beans.@RestController
: For RESTful web service provider beans.@ControllerAdvice
: Global exception handler for all controllers.@RestControllerAdvice
: Global exception handler for all REST controllers.Equivalent to <bean id class>
in XML.
SC interprets it and starts the bean lifecycle.
Examples:
package beans;
@Component("abc")
public class MyBean {...}
<bean id="abc" class="beans.MyBean"/>
@Component
public class MyBean {...}
<bean id="myBean" class="beans.MyBean"/>
scope
attribute in XML.lazy-init
attribute in XML.init-method
attribute in XML.destroy-method
attribute in XML.