Spring项目创建
maven方式创建:
- 创建maven java项目
- pom.xml添加Spring框架的依赖
- 创建beans.xml,声明需要Spring框架去自动实例化类成员的类,以及自动实例化的类
- 编写测试类,测试类中对象的自动实例化;classA持有classB,classA和classB都在beans.xml中进行声明,在测试类中通过context.getBean()的方式获取到classA的对象,调用classA.methodA()中调用classB.mehodB(),来验证classB被自动实例化成功
pom.xml中的dependency依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.3</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies>
applicationContext.xml配置
<?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="service" class="hello.MessagesService"></bean>
<bean id="printer" class="hello.MessagePrinter">
<property name="service" ref="service"></property>
</bean>
</beans>
applicationContext创建的位置,新建resources文件夹,设置为文件夹目录(项目创建后一般在main目录下会有resources资源目录)
applicationContext.xml创建的时候可以resource --New–XML Configuration File–Spring
要实例化的类MessagePrinter, MessagesService
package hello;
public class MessagePrinter {
private MessagesService service;
public MessagePrinter() {
System.out.println("MessagePrinter");
}
public MessagesService getService() {
return service;
}
//需要添加set方法,与applicationContext.xml中printer--property--name的值对应
public void setService(MessagesService service) {
this.service = service;
}
public void printMessage(){
System.out.println(service.getMessage());
}
}
package hello;
public class MessagesService {
public MessagesService() {
System.out.println("MessageService....");
}
public String getMessage(){
return "Hello World";
}
}
实例化ApplicationContext
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
MessagePrinter printer = context.getBean(MessagePrinter.class);
printer.printMessage();
运行结果:
对于Spring的理解:不用new去实例化对象,通过*.class对象就能够得到对象,并且只需要配置好applicationContext.xml,类中持有的对象也能够一并实例化
参考: