Home  >  Spring Core

Example of AnnotationConfigApplicationContext in Spring

By Arvind Rai, April 06, 2013
Bean in spring can be created in java file instead of XML,too. They are created with the help of @Configuration. And that application configuration is loaded by AnnotationConfigApplicationContext in spring container. AnnotationConfigApplicationContext has the register method that accepts the bean configuration class. AnnotationConfigApplicationContext provides the method getBean to get the bean object.

AppTest.java
package com.concretepage;
import java.sql.SQLException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class AppTest {
	public static void main(String[] args) throws SQLException {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
 
		ctx.register(AppConfig.class);
		ctx.refresh();

		Entitlement ent= (Entitlement)ctx.getBean("entitlement");
	    System.out.println(ent.getName());		
	    System.out.println(ent.getTime());
	
	}
}
 


AppConfig.java
package com.concretepage;

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

@Configuration
public class AppConfig  {
   
	@Bean(name="entitlement")
	public Entitlement entitlement(){
		Entitlement ent= new Entitlement();
		ent.setName("Entitlement");
		ent.setTime(20);
		return ent;
	}
}

 


Entitlement.java
package com.concretepage;

public class Entitlement {
	private String name;
	private int time;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getTime() {
		return time;
	}
	public void setTime(int time) {
		this.time = time;
	}
}
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us