使用AnnotationConfigApplicationContext可以实现基于Java的配置类加载Spring的应用上下文。避免使用application.xml进行配置。相比XML配置,更加便捷。
pom引入依赖:
代码语言:javascript复制org.springframeworkspring-context5.1.7.RELEASE
AppConfig.java
代码语言:javascript复制package com.kaigejava.config;
import com.kaigejava.Entitlement;
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(1);
return ent;
}
@Bean(name="entitlement2")
public Entitlement entitlement2() {
Entitlement ent= new Entitlement();
ent.setName("Entitlement2");
ent.setTime(2);
return ent;
}
}
注:
@Configuration可理解为用spring的时候xml里面的<beans>标签
@Bean可理解为用spring的时候xml里面的<bean>标签
Entitlement.java
代码语言:javascript复制package com.kaigejava;
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;
}
}
JavaConfigTest.java
代码语言:javascript复制package com.kaigejava;
import com.kaigejava.config.AppConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class JavaConfigTest {
public static void main(String[] arg) {
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());
Entitlement ent2 = (Entitlement)ctx.getBean("entitlement2");
System.out.println(ent2.getName());
System.out.println(ent2.getTime());
ctx.close();
}
}