Spring 的基本信息
:Spring 是一个开源框架
:Spring 是一个IOC(DI) 和AOP 容器的框架 (IOC反转控制,DI依赖注入)(AOP面向切面编程)
创建编写hello world
步骤一:创建项目
选择IDEA中Spring项目,创建Spring项目自动下载包,应该有18个包
步骤二:创建hello world
此hello 有一个方法输出hello 加上name
package com.chenx.spring.beans;
public class HelloWorld {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void hello(){
System.out.println("hello "+name);
}
}
一般而言我们想要设置name并且调用hello() 输出是采用如下方式
HelloWorld helloWorld= new HelloWorld();
helloWorld.setName("ccc");
helloWorld.hello();
在spring 中我们把创建HelloWorld对象和对属性复制交给spring完成
步骤三:创建配置Spring 的配置文件
创建applicationContext.xml配置文件
在配置文件中配置HelloWorld bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloWorld" class="com.chenx.spring.beans.HelloWorld">
<property name="name" value="ccc"></property>
</bean>
</beans>
步骤四:
第一步创建IOC容器
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
第二步从IOC容器中获取Bean实例
HelloWorld helloWorld=(HelloWorld) context.getBean("helloWorld");
第四步 输出
helloWorld.hello();
完整代码:
目录:
Main:
package com.chenx.spring.beans;
import javafx.application.Application;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld=(HelloWorld) context.getBean("helloWorld");
helloWorld.hello();
}
}