You are on page 1of 2

Date: 01/05/2020

Runners using Java Based Config


(by Mr.RAGHU)
javabyraghu@gmail.com
-----------------------------------------------------------------------------
*) In Spring boot, we can provide configuration in two different ways.
Those are:
a. Annotation Based configuration (@Component ...etc)
b. Java Based Configuration (@Configuration, @Bean..etc)

==> c. XML Config (Removed in Spring boot) <==

=> If class is defined by programmer(we have source code ie __.java )


then use Annotation based configuration only

=> If class is pre-defined then programmer will be having .jar-> .class files.
So, in this case we can inform to container create object using
JAVA BASED CONFIGURATION only.
----------------------------------------------------------------------------
*)Spring Java Based Configuration Steps:-

1. Define one public class with any name


2. Apply Annotation : @Configuration

3. Define one method (=one object in container)


with returnType as Classname/Interface(for which you need object),
method name behaves as objectName
4. Apply @Bean over method.

--Syntax----------------------------------------------------------
@Configuration
public class _______ {
@Bean
public <ClassName/Interface> <objectName>(){
//logic to create object
}
}
-----------Example---------------------------------------
class : Employee , variables: empId(int),empName(String)

-> Spring Java Based Config Code


package in.nit.config;

@Configuration
public class AppConfig {
@Bean
public Employee emp(){
Employee e=new Employee();
e.setEmpId(10);
e.setEmpName("A");
return e;
}
}
=========================Spring Boot Example=================================
1. Runner class code
package in.nit.runner;

import org.springframework.boot.CommandLineRunner;
public class MessageRunner implements CommandLineRunner{

@Override
public void run(String... args) throws Exception {
System.out.println("from message runner..");
}
}

2. java based config file


package in.nit.config;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import in.nit.runner.MessageRunner;

//ctrl+shift+O
@Configuration
public class AppConfig {

//no.of methods = no.of objects


@Bean
//public MessageRunner msObj() {
public CommandLineRunner msObj() {
return new MessageRunner();
//MessageRunner m=new MessageRunner();return m;
}
}

You might also like