Spring -> IOCxml使用注解的方式创建类对象(@Component,@Service,@Repository,@Controller)

1.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: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">
    <!--
    需要使用到context的命名
    标签名称:组件扫描描述:扫描类路径以查找自动注册为springbean的带注释组件。
    默认情况下,将检测到Spring提供的;
    @Component@Repository@Service@Controller@RestController@ControllerAdvice@Configuration原型。
    base-package格式(可以写一个总包的路径,也可以使用逗号隔开使用多个路径)
    -->
    <context:component-scan base-package="test10month.test1012"/>
    
    <!--附加:方式一:
    功能描述:只扫描xxx(这里是component)注解,不使用默认的都扫描
    include:包括   filter:过滤
    -->
    <context:component-scan base-package="test10month.test1012" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>
    </context:component-scan>
    
    <!--方式二:
    功能描述:除了xxx(这里是Service)不扫描以外,其他的都扫描
    exclude:排除   filter:过滤
    -->
    <context:component-scan base-package="test10month.test1012">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
    </context:component-scan>
</beans>

2.类

/**
 * 四个注解都可以使用,作用相同,都是给类创建对象
 * (value = "annotationSpring"),可以不写,默认为类的名字,首字母小写
 * value也可以不写,直接写"xxx",实现接口的时候最好写出具体名称
 */
@Component
@Service
@Repository
@Controller(value = "annotationSpring")
class AnnotationSpring {
  public void test() {
    System.out.println("注解测试");
  }
}

3.测试类

package test10month.test1012;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

/**
 * 功能描述:
 * @version 1.0
 * @className AnnotationSpringTest
 * @author: 罗德
 * @create: 2020-10-12 19:17
 */
public class AnnotationSpringTest {
  public static void main(String[] args) {
    var context = new ClassPathXmlApplicationContext("test10month/test1012/AnnotationSpring.xml");
    var annotationSpring = context.getBean("annotationSpring", AnnotationSpring.class);
    annotationSpring.test();
    /**
     * 注解测试
     */
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值