Spring入门之HelloSpring

Spring描述:
-轻量级:Spring是非侵入式的-基于Spring开发的应用中的对象可以不依赖于Spring的API
-依赖注入(DI---dependency injection,IOC)
-面向切面编程(AOP--aspect oriented programming)
-容器:Spring是一个容器,因为它包含并且管理应用对象的生命周期
-框架:Spring实现了使用简单的组件配置组合成一个复杂的应用,在Spring中可以使用XML和Java注解组合这些对象
-一站式:在IOC和AOP的基础上可以整合各种企业应用的开源框架和优秀的第三方类库(实际上Spring自身也提供了展示层的SpringMVC和持久层的Spring JDBC)

Spring架构图:

helloSpring的目录结构:

HelloSpring代码:

 1 package com.yl;
 2 
 3 public class HelloSpring {
 4 
 5     private String name;
 6     
 7     public HelloSpring(){
 8         System.out.println("HelloSpring's 构造方法");
 9     }
10     
11     public void setName(String name) {
12         System.out.println("setName:" + name);
13         this.name = name;
14     }
15     
16     public void hello() {
17         System.out.println("Hello : " + name);
18     }
19 
20 }

Main代码:

 1 package com.yl;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 public class Main {
 7     public static void main(String[] args) {
 8         
 9         /*//创建HelloSpring对象
10         HelloSpring helloSpring = new HelloSpring();
11         //为name属性赋值
12         helloSpring.setName("Spring");*/
13         
14         //1.创建Spring的IOC容器--调用bean的构造方法和setName方法
15         ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
16         //2.从IOC容器中获取Bean实例
17         HelloSpring helloSpring = (HelloSpring)ctx.getBean("helloSpring");
18         //3.调用hello方法
19         helloSpring.hello();
20     }
21 }

applicationContext.xml文件:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 5 
 6     <!-- 配置bean -->
 7     <bean id="helloSpring" class="com.yl.HelloSpring">
 8         <property name="name" value="Spring"></property>
 9     </bean>
10     
11 </beans>
原文地址:https://www.cnblogs.com/dreamfree/p/4077223.html