Bean Configuration - bhudevi0924/Spring-boot GitHub Wiki
- Beans configuration is defined as the process of defining and configuring the beans.
-
Annotation based configuration: (Implicit Bean Discovery)
-
Different annotations used in application are @Controller, @Service, @Repository, @Controller. These annotations are used to defining various layers of files. Based on these annotation, the files are configured as managed by spring beans and the spring will automatically create a bean.
-
@Autowired annotation can be used for injecting dependencies automatically.
package com.example.demo.services; import org.springframework.stereotype.Service; @Service public class Service_Name { public void metho_name() { System.out.println("Creates bean."); } }
-
-
Java Configuration: (Programmatic configuration of beans)
-
Define a bean using "@Bean" annotation within a Java configuration class annotated with "@Configuration".
package com.example.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.example.demo.services.MyService; @Configuration public class AppConfig { @Bean public MyService myService() { return new MyService(); } }
-
-
XML Configuration:
-
Uses Xml configuration files (eg: applicationContext.xml) to define beans and their dependencies.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Define a bean for MyService --> <bean id="myService" class="com.example.demo.services.MyService"/> </beans>
-