Spring框架一直以来是Java开发中的耀眼明星,其IOC/AOP能够大大下降代码的耦合度,但低版本中的xml配置繁杂也让不少人诟病;java
Spring4.x以上已经提倡基于注解的开发模式,在非Web项目中,"基于spring纯注解方式如何开发?"就是本文要说明的内容,且看下文:web
下面基于Eclipse Oxygen版本,开发一个普通的Java工程,演示以下:spring
1. 基于 maven-archetype-quickstart 骨架 建立一个普通的Maven工程:json
2. 在pom.xml中加入spring、logback及经常使用jar包的依赖:springboot
3. 在src/main/resources下建立 application.properties、logback.xml、assembly.xml 等配置文件app
4. 在Java 代码中建立 @Configuration、@PropertySource 类用于加载配置框架
package com.morpheus.cmdline.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration @PropertySource(value = "classpath:application.properties", ignoreResourceNotFound = false, encoding = "UTF-8") public class AppConfiguration { @Value("${cmd.decrypt.key}") private String decryptKey = null; @Value("${cmd.encrypt.key}") private String encryptKey = null; public AppConfiguration() { } public String getDecryptKey() { return decryptKey; } public String getEncryptKey() { return encryptKey; } }
5. 在Java 代码中编写 @Component、@Service 等基本组件类maven
6. 在Java 代码中使用 @Autowired、@Resource 等注入依赖Beanui
7. 在Java 代码中使用 @Value 等注入配置值spa
8. 在主入口类中使用 AnnotationConfigApplicationContext 类启动 spring容器,并经过 getBean() 方法获取须要执行的Bean
package com.morpheus.cmdline; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.alibaba.fastjson.JSONObject; import com.morpheus.cmdline.cmd.CmdInvoker; /** * 普通Java应用(非web)入口类 */ public class Application { public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext("com.morpheus.cmdline"); try { CmdInvoker cmdInvoker = (CmdInvoker) applicationContext.getBean("cmdInvoker"); JSONObject resJSON = cmdInvoker.invoke(args); System.out.println(resJSON); } catch (Throwable th) { th.printStackTrace(); } finally { applicationContext.close(); } } }
9. 使用 maven-jar-plugin、 maven-dependency-plugin 打包项目为可执行的jar包
java %JVM_OPTS% -jar CmdLine.jar
就能够执行咯
10. 使用 maven-assembly-plugin 打包项目为可部署的zip包
而后就万事大吉了,能够看到在本项目中不使用任何一个 spring 的xml配置,所有基于注解方式;
在以上步骤开发中,除了第 8 步骤以外,其余步骤一样适用于 springboot 项目的开发。。。
截图后面再补充,准备睡觉咯。。。