Spring基于注解管理bean

Spring基于注解管理bean

和 XML 配置文件一样,注解本身并不能执行,注解本身仅仅只是做一个标记,具体的功能是框架检测到注解标记的位置,然后针对这个位置按照注解标记的功能来执行具体操作。
本质上:所有的一切操作都是由Java代码完成的,XML和注解只是告诉框架中的Java代码如何执行

注解

@Component:将类标识为普通组件
@Controller:将类标识为控制层组件
@Service:将类标识为业务层组件
@Repository:将类标识为持久层组件

注:通过查看源码我们得知,@Controller、@Service、@Repository这三个注解只是在@Component注解
的基础上起了三个新的名字,让我们能够便于分辨组件的作用。

扫描

Spring 为了知道程序员在哪些地方标记了什么注解,就需要通过扫描的方式,来进行检测。然后根据注解进行后续操作
使用注解的方式需要在配置文件中配置扫描,通过注解+扫描所配置的bean的id,默认值为类的小驼峰,即类名的首字母为小写的结果(可以通过标识组件注解的value属性值自定义id)

以下为具体的代码实现

@Controller
public class UserController {
}
public interface UserService {
}
@Service
public class UserServiceImpl implements UserService {
}
public interface UserDao {
}
@Repository
public class UserDaoImpl implements UserDao {
}

这里需要特别注意,context:exclude-filter标签里的type属性可以设置排除扫描的类型,使用的比较多的就是:(annotation:根据注解类型进行排除),以后在整合Spring MVC中就会用到。至于包含扫描十分鸡肋了解即可

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--
        1.context:exclude-filter:排除扫描
         type:设置排除扫描的方式
         type=“annotation|assignable”
          annotation:根据注解类型进行排除,expression中需要设置排除注解的全类名
          assignable:根据类的类型进行排除,expression中需要设置排除的类的全类名

        2.context:include-filter:包含扫描(实际中意义不大)
         注意:需要在context:component-scan标签中设置use-default-filters="false"
         use-default-filters="true"(默认),所设置的包下所有的类都需要扫描,此时可以使用排除扫描
         use-default-filters="false",所设置的包下所有的类都不需要扫描,此时才可以使用包含扫描
    -->

    <!--扫描组件-->
    <context:component-scan base-package="com.qcw.spring"></context:component-scan>
//    <context:component-scan base-package="com.qcw.spring" use-default-filters="false">-->
//        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>-->
//&lt;!&ndash;        <context:exclude-filter type="assignable" expression="com.qcw.spring.controller.UserController"/>&ndash;&gt;-->

//&lt;!&ndash;        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>&ndash;&gt;-->
//    </context:component-scan>-->

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值