spring 中各个配置文件的说明
(1)pom.xml
pom.xml文件是在整个项目下面,该xml的主要作用是:导入框架的jar包及其所依赖的jar包,导入的jar包是写在<dependencies></dependencies>中
<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>oracle.MavenPro</groupId> <artifactId>MyFirstPro</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework/spring-core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.1.1.RELEASE</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.1.RELEASE</version> </dependency> </dependencies> </project>
(2)spring.xml
spring.xml是通过spring框架来创建对象,而不需要在类中创建对象。
下面通过一个简单的sayhello例子来说明:
定义一个接口 ISayHello
package com.service; public interface ISayHello { public void sayHello(); }
定义 接口ISayHello 的实现类 SayHelloImple
package com.service.imple; import com.service.ISayHello; public class SayHelloImple implements ISayHello{ @Override public void sayHello() { System.out.println("hello!!!"); } }
通过spring.xml来实例化对象,其中class属性是实现类的全路径,id是实例化对象的别名(hello)。
<?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-3.0.xsd"> <bean id="hello" class="com.service.imple.SayHelloImple"></bean> </beans>
其中下面这段代码是告诉spring,通过什么编码来解析<bean>
新建一个test类
package com.service; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.service.imple.SayHelloImple; public class Test { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); SayHelloImple sayhello = (SayHelloImple) context.getBean("hello"); sayhello.sayHello(); } }
下面这段代码是加载 spring.xml 文件
ApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
下面代码是获取实例化的对象hello
SayHelloImple sayhello =
(SayHelloImple) context.getBean("hello");
运行结果为: