2.2 Spring 的第一个程序
项目结构展示
2.2.1 创建 maven 项目
2.2.2 引入 maven 依赖 pom.xml
4.0.0 com.it ch1-Hello-Spring1.0-SNAPSHOT ch1-Hello-Spring http://www.example.com UTF-8 1.8 1.8 junit junit4.11 test org.springframework spring-context5.2.5.RELEASE maven-clean-plugin 3.1.0 maven-resources-plugin 3.0.2 maven-compiler-plugin 3.8.0 maven-surefire-plugin 2.22.1 maven-jar-plugin 3.0.2 maven-install-plugin 2.5.2 maven-deploy-plugin 2.8.2 maven-site-plugin 3.7.1 maven-project-info-reports-plugin 3.0.0
2.2.3 定义接口与实体类
1.接口
package com.it.service;
public interface SomeService {
void doSome();
}
2.实体类
package com.it.service.Impl;
import com.it.service.SomeService;
public class SomeServiceImpl implements SomeService {
public SomeServiceImpl() {
System.out.println("SomeServiceImpl的无参构造方法");
}
@Override
public void doSome() {
System.out.println("执行了SomeServiceImpl的doSome()方法");
}
}
2.2.4创建
Spring
配置文件
在
src/main/resources/
目录现创建一个
xml
文件,文件名可以随意,但
Spring 建议的名
称为
applicationContext.xml
。
spring
配置中需要加入约束文件才能正常使用,约束文件是
xsd
扩展名。
package com.it;
import static org.junit.Assert.assertTrue;
import com.it.service.Impl.SomeServiceImpl;
import com.it.service.SomeService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Date;
public class AppTest
{
@Test
public void test1(){
SomeService service = new SomeServiceImpl();
service.doSome();
}
//在创建spring容器时,会创建配置文件中所有的对象。
@Test
public void test2(){
//指定spring文件的的名称
String config="beans.xml";
//创建表示的spring容器对象
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(config);
//从容器中获取某个对象
SomeService someService = (SomeService) applicationContext.getBean("someService");
//使用spring创建好的对象
someService.doSome();
}
@Test
public void test3(){
String config="beans.xml";
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(config);
//获取容器中定义对象的数量
int nums = applicationContext.getBeanDefinitionCount();
System.out.println("在容器中定义的对象的数量:"+nums);
// 容器中每个定义对象的名字
String[] names = applicationContext.getBeanDefinitionNames();
for (String stu:names){
System.out.println(stu);
}
}
@Test
public void test4(){
String config="beans.xml";
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(config);
Date myDate = (Date) applicationContext.getBean("myDate");
System.out.println("时间:"+myDate);
}
}
1.test1()结果,没有使用spring容器
2.test2()结果,使用spring容器。在创建spring容器时,会创建配置文件中所有的对象,创建这些对象时会再次调用无参构造方法。
3.test3()结果,使用spring容器。在创建spring容器时,会创建配置文件中所有的对象,创建这些对象时会再次调用无参构造方法。4.使用 spring 创建非自定义类对象 的测试结果
2.2.7 容器接口和实现类
ApplicationContext 用于加载 Spring 的配置文件,在程序中充当“容器”的角色。其实现 类有两个。A、配置文件在类路径下
若 Spring 配置文件存放在项目的类路径下,则使用 ClassPathXmlApplicationContext 实现 类进行加载。B、 ApplicationContext 容器中对象的装配时机
ApplicationContext 容器,会在容器对象初始化时,将其中的所有对象一次性全部装配好。 以后代码中若要使用到这些对象,只需从内存中直接获取即可。执行效率较高。但占用内存。 C 、 使用 spring 容器创建的 java 对象



