Loading
 
What's Next: View All Tutorial →

Java based Configuration using AnnotationConfigApplicationContext and @Bean

A simple program to create a java based configuration project without xml configuration App.java Starting point of program.   package com.demo.spring; import org.springframework.cont...

Published Date: 03/09/2018  Last Modified Date: 03/09/2018    New Post



A simple program to create a java based configuration project without xml configuration

App.java


Starting point of program.

 
package com.demo.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.demo.spring")
public class App {

	public static void main(String args[]) {
		ApplicationContext ctx = new AnnotationConfigApplicationContext(App.class);

		// calcSerivce bean is created and referred by using @Service
		CalcService calc = (CalcService) ctx.getBean("calcService");
		System.out.println(calc.add(1, 2));

		// calcService2 bean is created and referred by using @Bean
		CalcService calc2 = (CalcService) ctx.getBean("calcService2");
		System.out.println(calc.add(3, 4));

	}

	// To create a bean using @Bean
	@Bean
	public CalcService calcService2() {
		return new CalcService();
	}

}

Keywords to highlight

@Configuration

@ComponentScan

@basePackages

AnnotationConfigApplicationContext()
 

CalcService.java

package com.demo.spring;

import org.springframework.stereotype.Service;

@Service
public class CalcService {

	public int add(int x, int y) {

		return x + y;
	}

}
 

OutPut:


15:35:03.738 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'calcService'
3
15:35:03.738 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'calcService2'
7


 
Awaiting for Administrator approval




← Back to list


Related Post




×