3.Spring项目的搭建与配置

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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值