java配置是Spring4.x推荐的配置方式,可以完全代替xml配置,java配置是通过@Configuration和@Bean来实现的。@Configuration声明当前类是一个配置类,相当于Spring配置的xml文件,@Bean注解在方法上,声明当前方法的返回值为一个Bean。
下面是自己使用java配置搭建Spring项目的demo:
1、IDE:spring tool suite,构建工具:maven,新建maven工程,注意spring和jdk的版本兼容问题,pom.xml文件
4.0.0
powerx.io
spring4javaconfig
0.0.1-SNAPSHOT
1.8
org.springframework
spring-context
5.0.7.RELEASE
org.apache.maven.plugins
maven-compiler-plugin
2.3.2
${java.version}
${java.version}
2、功能类的bean,其中StudentService使用@Bean方式由spring容器生成单例对象并存储,UserService使用注解方式由spring容器生成单例对象并存储,两种方式是等价的,并且在UserService中使用@autowired注解有容器为其属性studentService赋值进行初始化,这也是spring的核心技术之一IOC(依赖注入)。
packagepowerx.io.service;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;
@Servicepublic classUserService {
@Autowired//注入studentService
privateStudentService studentService;public voidsysout() {
System.out.println("spring");
}public voidsay() {
studentService.say();
}
}
packagepowerx.io.service;public classStudentService {public voidsay() {
System.out.println("I am student");
}
}
3、java配置文件
packagepowerx.io;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.ComponentScan;importorg.springframework.context.annotation.Configuration;importpowerx.io.service.StudentService;
@ComponentScan("powerx.io")//自动扫描报名下所有使用@Service、@Component、@Repository和@Controller注解的类,并注册为bean
@Configurationpublic classJavaConfig {
@Bean//使用@Bean在java配置中定义bean,所以StudentService类无需加@Service注解
publicStudentService studentService() {return newStudentService();
}
}
4、主类,加载spring容器,调用bean完成功能
packagepowerx.io;importorg.springframework.context.annotation.AnnotationConfigApplicationContext;importpowerx.io.service.UserService;public classMain {public static voidmain(String[] args) {
AnnotationConfigApplicationContext context= new AnnotationConfigApplicationContext(JavaConfig.class);
UserService us= context.getBean(UserService.class);
us.sysout();
us.say();
context.close();
}
}
使用java配置搭建Spring项目非常方便,在实际应用中(非web项目),我们可以通过改造此demo来完成特定的功能,更好的管理我们的bean,以此使我们的项目更加稳定。