首先Spring是什么?
轻量级:Spring是非侵入性-基于Spring开发的应用中的对象可以不依赖于Spring的API
依赖注入 DI:dependency injection、IOC
面向切面编程:AOP aspect oriented programming
容器:Spring是一个容器,因为包含并且管理应用对象的生命周期
框架:Spring 实现了使用简单的组件配置组合成一个复杂的应用。在Spring中可以使用xml和java注解组合这些对象
一站式:在IOC和AOP的基础上可以整合各种企业应用的开源框架和优秀的第三方类库(实际上Spring自身也提供了展现层的Spring MVC和持久层的Spring JDBC)
HelloWorld第一个程序
首先新建一个HelloWorld类
public class HelloWorld {
private String name;
public String getName() {
return name;
}
public void setName2(String name) {
System.out.println("setName2:"+name);
this.name = name;
}
public void hello(){
System.out.println("Hello:" + name);
}
public HelloWorld(){
System.out.println("HelloWorld's Constructor...");
}
}
接着在新建一个ApplicationContext.xml
<!-- 配置bean 其中的property中的name属性是根据类中的setter方法中名字决定的-->
<!--
在Class:bean的全类名中,通过反射的方式在IOC容器中创建
Bean,必须要使用一个无参数的构造器,而不能是带参数的 。
id:标识容器中的bean,id必须是唯一的
property:利用属性注入
-->
<bean id="helloworld" class="com.spring.beans.HelloWorld">
<property name="name2" value="Spring"></property>
</bean>
最后新建一个测试类,测试HelloWorld类中的方法,经过测试,控制台会出现hello spring.
//1、创建Spring的IOC容器对象
//2、ApplicationContext 代表IOC容器
//3、ClassPathXmlApplicationContext:是ApplicationContext接口的实现类,该实现类
//从类路径下来加载配置文件。
ApplicationContext ctx = new ClassPathXmlApplicationCon.text("applicationContext.xml");
//2、从 IOC 容器中获取bean实例,
//通过id 定位到 IOC 容器中的bean
//HelloWorld helloworld = (HelloWorld) ctx.getBean("helloworld");
//利用类型返回 IOC 容器中的Bean,但要求 IOC 必须能有一个该类型的Bean
HelloWorld helloworld = ctx.getBean(HelloWorld.class);
System.out.println(helloworld);
//3、调用hello方法
helloworld.hello();