3.Spring项目的搭建与配置
1.导入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.7</version>
</dependency>
2.配置元数据
Spring IoC容器使用一种形式的配置元数据。这个配置元数据表示您作为应用程序开发人员如何告诉Spring容器实例化,配置和组装应用程序中的对象。
- 基于注释的配置:Spring 2.5引入了对基于注释的配置元数据的支持。
- 基于Java的配置:从Spring 3.0开始,Spring JavaConfig项目提供的许多功能已成为核心Spring Framework的一部分。因此,您可以使用Java而不是XML文件来定义应用程序类外部的bean。
以下示例显示了基于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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
该id 属性是标识单个bean定义的字符串。 | |
---|---|
该class 属性定义Bean的类型并使用完全限定的类名。 |
代码示例的beans.xml
<?xml version="1.0" encoding="UTF8"?>
<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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用spring创建对象 在Spring中这些都称为bean-->
<bean id="hello" class="com.liu.pojo.Hello"> <!--bean为一个对象-->
<!--
id = 变量名
class = new的对象
property是给对象中的属性设值
-->
<property name="name" value="Spring"></property>
</bean>
</beans>
3.实例化容器
提供给ApplicationContext
构造函数的一个或多个位置路径是资源字符串,这些资源字符串使容器可以从各种外部资源(例如本地文件系统,Java等)中加载配置元数据CLASSPATH
。
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
Hello代码示例
public class BaseTest {
@Test
public void test() {
/*获取spring的上下文对象*/
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
/*现在对象已经都由spring管理了 通过getBean新建Hello的示例*/
Hello hello = (Hello) context.getBean("hello");
//新建一个com.liu.pojo.Hello对象 hello(bean的id) name属性的值为Spring(property)
hello.show();
}
}