JavaEE——Spring4--(1)搭建Spring开发环境 以及在IDEA中导入jar包
IntelliJ IDEA 中如何导入jar包(以引入spring包,构建spring测试环境为例)
1、
2、
3、这时候IntelliJ IDEA就会自动下载Spring所需要的jars,只需要等待就好。
4.相应的jar包已经自动下载好了
5.新建Spring配置文件

框架的作用:首先创建一个HelloWorld类,有一个name属性,还有一个sayHello的方法,还有一个setter方法用来设置name属性。

在我们不使用框架的时候,也就是平常的编程中,我们要调用sayHello这个方法,可以分为3步。
1. 创建一个HelloWorld的实例对象
2. 设置实例对象的name属性
3. 调用对象的sayHello()方法

接下来我们就要使用Spring了,首先在Spring的配置文件中加入如下内容。
<?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-->
<bean id="helloworld" class="bean.HelloWorld">
<property name="name" value="Spring"></property>
</bean>
</beans>
运行使用Spring
使用了Spring的IOC功能,把对象的创建和管理的功能都交给了Spring去管理,我们需要对象的时候再和Spring去要就行
package bean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args){
/* HelloWorld helloWorld = new HelloWorld();
helloWorld.setName("Skye");
helloWorld.hello();*/
//1. 创建 Spring 的 IOC 容器
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("spring-config.xml");
//2. 从 IOC 容器中获取 bean 的实例
HelloWorld helloWorld = (HelloWorld) applicationContext.getBean("helloworld");
//3. 使用 bean 调用hello方法
helloWorld.hello();
}
}
1.加入

浙公网安备 33010602011771号