一、spring介绍
spring就是一个容器,拿东西,然后找他要东西
二、spring搭建
1、新建动态web项目,在src下创建applicationContext.xml文件
2、在WEB-INF下新建文件夹lib,再导6个包
3、容器就得有对象,创建一个User对象,放入src下,其代码如下所示:
package cn.itcast.bean;
public class User {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
4、书写配置文件,注册对象到容器,applicationContext.xml配置文件如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd ">
<!-- 将User对象将给Spring容器管理 -->
<bean name="user" class="cn.itcast.bean.User"/>
</beans>
注意:applicationContext.xml下约束导入可详见https://blog.csdn.net/weixin_40521823/article/details/84856841
5、代码测试Demo,在src下,测试是否能从spring容器中拿到对象,代码如下所示:
package cn.itcast.a_hello;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.bean.User;
public class Demo {
@Test
public void fun1() {
//1、创建容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//2、向容器“要”user对象
User u = (User) ac.getBean("user");
//3、打印user对象
System.out.println(u);
}
}
6、测试结果:
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
cn.itcast.bean.User@7113b13f