Spring 是一个 IOC(DI)和AOP的框架

image.png

Spring 是什么

  • 轻量级,Spring是非侵入性的,基于Spring开发的应用中对象可以不依赖于Spring的API
  • 依赖注入
  • 面向切面编程
  • 容器,Spring是一个容器,因为它包含并且管理应用对象的生命周期
  • 框架,Spring实现了使用简单的组建配置组合成一个复杂的应用,在Spring中可以使用XML和Java的注解组合这些对象
  • 一站式,在IOC和AOP的基础换行可以整合各种企业应用的开源框架和优秀的第三方类库,SpringMVC,Spring JDBC,Mybatis…

Spring Hello World

  1. // src/com/lijunyang/model/HelloWorld.java
  2. public class HelloWorld {
  3. private String name;
  4. public void setName(String name) {
  5. this.name = name;
  6. }
  7. public String getName() {
  8. return this.name;
  9. }
  10. public String hello() {
  11. System.out.println("Hello: " + this.name);
  12. }
  13. }
  14. // src/com/lijunyang/model/Main.java
  15. public class Main {
  16. public static void main(String[] args) {
  17. HelloWorld hello = new HelloWorld();
  18. hello.setName("lijunyang");
  19. hello.hello();
  20. // "Hello: lijunyang"
  21. }
  22. }
  1. // src/applicationCentext.xml
  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <beans xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="
  7. http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  11. <bean id="helloWorld" class="com.lijunyang.model">
  12. <property name="name" value="Spring"></property>
  13. </bean>
  14. </beans>
  15. // src/com/lijunyang/model/Main.java
  16. public class Main {
  17. public static void main(String[] args) {
  18. // 创建 Spring IOC容器
  19. org.springframework.context.ApplicationContext ctx =
  20. new ClassPathXmlApplicationContext("applicationContext.xml");
  21. // 从容器中取出 Bean实例
  22. HelloWorld hello = (HelloWorld) ctx.getBean("helloWorld");
  23. hello.hello();
  24. // "Hello: Spring"
  25. }
  26. }
  1. // src/com/lijunyang/model/HelloWorld.java
  2. public class HelloWorld {
  3. private String name;
  4. public HelloWorld() {
  5. System.out.println("HelloWorld`s Constructor");
  6. }
  7. public void setName(String name) {
  8. System.out.println("setName:" + name);
  9. this.name = name;
  10. }
  11. public String getName() {
  12. return this.name;
  13. }
  14. public String hello() {
  15. System.out.println("Hello: " + this.name);
  16. }
  17. }
  18. // src/com/lijunyang/model/Main.java
  19. public class Main {
  20. public static void main(String[] args) {
  21. org.springframework.context.ApplicationContext ctx =
  22. new ClassPathXmlApplicationContext("applicationContext.xml");
  23. // 此时输出
  24. // HelloWorld`s Constructor
  25. // setName: Spring
  26. }
  27. }