在实际工作中大部分企业级开发都是web项目然后继承spring、springmvc,或者使用springboot来搭建web项目。然后使用@Sevice,@Controller,@Autowired等注解来进行实际业务代码的开发。然而在实际情况中可能有很多时候要开发非web项目的一些普通java应用。我们怎么使用spring来快速大家我们的应用呢?
工程代码已经放到github上了,项目地址https://github.com/wpf008/Application
首先引入spring依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
这是我们工程以普通java应用从dao->service->main函数调用service方法为例搭建:
首先创建一个UserDao
@Repository
public class UserDao {
//这里可以 @Autowired 来注入SqlSession
// 然后findById方法可以真正从数据库获取数据
public User findById(){//模拟从数据库查数据等
User user =new User();
user.setId("2019");
user.setName("pengfei.wang");
user.setAge(25);
return user;
}
}
创建UserService接口
public interface UserService {
User findById();
}
然后实现UserService
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
public User findById() {
return userDao.findById();
}
}
最后在Application主函数里调用UserService方法
@ComponentScan
public class Application {
/**
* 注意四点
* ①Application使用了@ComponentScan
* ②Application这个类的位置是不是和spring boot的启动类位置很相似
* ③这里ComponentScan默认basePackages是com.wpf
* ④如果你的启动类放在其他包下面记得@ComponentScan里你要写你要扫描的包路径
* 不然@ComponentScan默认是到自己类路径的。
* 可以见com.wpf.app.Main
*/
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = null;
try {
applicationContext = new AnnotationConfigApplicationContext(Application.class);//初始化IOC容器
UserService userService = applicationContext.getBean(UserService.class);//通过IOC容器获得你要执行的业务代码的类
User user = userService.findById();//通过IOC容器获取到的类执行你的业务代码
System.out.println(user);
} finally {
if (applicationContext != null){
applicationContext.close();
System.out.println("普通java程序执行完成,IOC容器关闭。。。");
}
}
}
}
注意:Application这个类是放在包的根目录下,所以@ComponentScan是扫描根包下所有使用注解得Bean,如果你的主函数入口放在其他包下面,那么请在@ComponentScan加入包扫描路径。
此时一个分web项目的java应用程序就搭建好了,如果平时企业里有一些非wen项目像java写的定时batch等可以使用spring来快速构建然后整合mybatis等其它框架来快速实现自己的业务代码。