1. 最简单的JavaConfig配置例子
核心是@Configuration和@bean标签
下面我们把一个Car类注册为bean,并取出调用其getName()
普通的POJO Car.java:
package com.test.spring;
public class Car {
//设置一个默认值
private String name ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Car() {
System.out.println("car loaded....");
}
}
配置类MainConfig.java :
package com.test.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MainConfig {
@Bean
public Car car(){
Car car = new Car();
//设置一个默认值
car.setName("car");
return car;
}
}
main方法执行类MainStart.java:
package com.test.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainStart {
public static void main(String[] args) {
// 加载spring上下文
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
Car car = (Car) context.getBean("car");
System.out.println(car.getName());
}
执行结果:
car
分析:我们成功的把一个Car类注册为bean,从中我们看到,通过AnnotationConfigApplicationContext,可以替代classpathxmlapplicationcontext,并且完全不用xml即可完成spring注入功能。
上面例子有个弊端,只能通过@bean定制注册bean的过程,那么和以前的@Component等注解方式兼容吗?当然支持
2. 如何兼容@Component等注解
记得以前我们怎么让注解生效吗?只需要在xml中增加开关:
<context:component-scan base-package="XX.XX"/>
同样的,在JavaConfig中,要使用组件扫描,仅需用@ComponentScan进行注解即可:
@Configuration
@ComponentScan(basePackages = "com.somnus")
public class AppConfig {
...
}
2.1 演示@ComponentScan
修改 MainConfig.java 配置类,增加@ComponentScan定义扫描路径"com.test.spring":
package com.test.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* 定义扫描的路径,路径下带声明标签的类均会被解析
*/
@Configuration
@ComponentScan(basePackages = {
"com.test.spring"})
public class MainConfig {
}
在@ComponentScan定义的路径下,会被注册到容器中,因此新增一个AnotherCar类,并加上@Component注解:
package com.test.spring;
import org.springframework.stereotype.Component;
@Component
public class AnotherCar {
public AnotherCar() {
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
main方法执行类MainStart.java:
package com.test.spring;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MainStart {
public static void main(String[] args) {
// 加载spring上下文
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
Car car = (Car) context.getBean("car");
System.out.println(car.getName());
}
执行结果:
car
com.test.spring.AnotherCar@15bfd87
AnotherCar不为null,说明AnotherCar注册成功了!