Spring context名称空间的使用

目录

一、外部 properties 属性文件引入到 spring 配置文件中

properties文件

spring配置文件

1.引入 context 名称空间

2.引入外部属性文件

3.配置连接池

二、注解方式实现对象创建

1.引入spring-aop jar包

2.引入 context 名称空间(同上)

3.开启组件扫描:

4.创建类,在类上添加创建对象注解

5.测试

6.开启组件扫描细节配置


一、外部 properties 属性文件引入到 spring 配置文件中

properties文件


spring配置文件

1.引入 context 名称空间

xmlns:context="http://www.springframework.org/schema/context" 
xsi:schemaLocation="http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context.xsd"

2.引入外部属性文件

<context:property-placeholder location="classpath:jdbc.properties"/>

3.配置连接池

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="${prop.driverClass}"></property>
            <property name="url" value="${prop.url}"></property>
            <property name="username" value="${prop.userName}"></property>
            <property name="password" value="${prop.password}"></property>
</bean>

二、注解方式实现对象创建

1.引入spring-aop jar包

2.引入 context 名称空间(同上)

3.开启组件扫描:

如果扫描多个包

①多个包使用逗号隔开

<context:component-scan base-package="com.atguigu.spring5.dao,com.atguigu.spring5.service"></context:component-scan>

②扫描包上层目录

<context:component-scan base-package="com.atguigu.spring5"></context:component-scan>

4.创建类,在类上添加创建对象注解

①在注解里面 value 属性值可以省略不写,默认值是类名称,首字母小写

UserService -- userService

②注解可以写其他注解Service、Controller、Respository

package com.atguigu.spring5.service;

import org.springframework.stereotype.Component;

@Component(value = "userService")
public class UserService {
    public void add(){
        System.out.println("service add........");
    }
}

5.测试

    @Test
    public void testService(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService", UserService.class);
        System.out.println(userService);
        userService.add();

    }

结果

6.开启组件扫描细节配置

示例 1
 use-default-filters="false" 表示现在不使用默认 filter,自己配置 filter
 context:include-filter ,设置扫描哪些内容

    <context:component-scan base-package="com.atguigu.spring5" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

示例 2
下面配置扫描包所有内容  默认use-default-filters="true"
context:exclude-filter: 设置哪些内容不进行扫描

    <context:component-scan base-package="com.atguigu.spring5">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值