java spring 工程_使用java配置来构建spring项目

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,以此使我们的项目更加稳定。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值