基于注解的方式配置Bean

Spring中配置bean的注解

1.@Component:基本注解

2.@Service:一般用于服务层

3.@Repository:用于标识持久层组件,一般与数据库操作相关的bean使用此注解

4.@Controller:用于表现层

使用注解配置bean

需要用到context命名空间。

1.在声明类的时候添加注解

package com.ustc.yi.annotation.controller;

import com.ustc.yi.annotation.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * Created by Yi on 2019/5/27.
 */
@Controller
public class UserController {

   
    public void execute(){
        System.out.println("UserController execute...");
    }
}

2.在xml配置文件中使用<context:component-scan>来指定要扫描的包,IOC容器会扫描该包及其子包,扫描到的包中的类如果添加了注解,IOC容器会为其生成bean,bean的名字为该类的名字首写字母小写,另外也可以在注解中指定bean的名字,如@Component("指定的bean的名字")。另外可以使用resource-pattern来指定要扫描的资源,如指定只生成带有@Repository注解的.class文件,这样不会生成其他的bean

<!--指定Spring IOC容器扫描的包-->
    <!--可以通过resource-pattern指定扫描的资源-->
    <context:component-scan base-package="com.ustc.yi.annotation"
            resource-pattern="repository/*.class"
            />

3. 可用context:exclude-filter指定排除哪些表达式的组件

    context:include-filter指定包含哪些表达式组件,需要配合use-default-filters使用 (设置为true)

    使用这两个时,可以指定

    type为annotation:根据注解来排除或包含哪些类

    type为assignable:根据类名来排除或包含哪些类

<context:component-scan base-package="com.ustc.yi.annotation"
                       resource-pattern="repository/*.class"
            >
        <!--<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
        <context:exclude-filter type="assignable" expression="com.ustc.yi.annotation.repository.UserRepository"/>-->
        <context:include-filter type="assignable" expression="com.ustc.yi.annotation.repository.UserRepository"/>
    </context:component-scan>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值