pom.xml:里面存放了所需jar包的依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zm</groupId>
<artifactId>SpringDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--Spring的依赖包-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<!--Spring必须的4个jar包:beans,context,expression,core-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>4.3.12.RELEASE</version>
</dependency>
<!--============================================================-->
<!--日志jar包依赖-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
application.xml: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 id="hello" class="com.zm.bean.HelloWorld">
<property name="name" value="Betty"></property>
</bean>
</beans>
测试类:
package com.zm.bean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
@Test
public void test01() {
/*传统方式创建Bean对象*/
HelloWorld hello = new HelloWorld();
hello.setName("Betty");
hello.sayHello();
}
@Test
public void test02(){
//1.创建Spring IOC容器 执行了无参构造方法和setXXX方法
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:application.xml");
//2.从IOC容器中获取Bean对象
// HelloWorld bean = context.getBean(HelloWorld.class);
//3.调用HelloWorld实例对象中的sayHello()方法
// bean.sayHello();
}
}
当注释了2,3步,运行的结果如下。说明Spring在创建IOC容器的过程中,执行了无参构造方法和setxxx()属性注入。