11.注解扫描器.md

zhanglei 2022年05月30日 667次浏览

11.注解扫描器

UserService类

package Spring5.UserService;

import org.springframework.stereotype.Component;

@Component(value="userService")
//与<bean id="userService" class="Spring.UserService.UserService"等效
//如果括号内为空,那么value值即id值默认为 首字母小写后的类名
public class UserService {
    public void add(){
        System.out.println("add......");
    }
}

bean10.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"
       xmlns:p="http://www.springframework.org/schema/p"
       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
        http://www.springframework.org/schema/context/spring-context.xsd"
        >
<!--见UserService包-->
<!--开启组件扫描:即申明 所加注解的类 所在的包的位置-->
    <context:component-scan base-package="Spring5"></context:component-scan>
    <!--实例一 不使用默认的filter,只扫描Component注解-->
    <context:component-scan base-package="Spring5" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>
    </context:component-scan>

    <!--实例二 使用默认的filter,全扫描,但不扫描Component注解-->
    <context:component-scan base-package="Spring5" use-default-filters="true">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Component"/>
    </context:component-scan>
</beans>

测试类

public class TEST {

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

测试结果

Spring5.UserService.UserService@5a59ca5e
add......