2.组件注册-@ComponentScan-自动扫描组件&指定扫描规则

包扫描规则
添加了以下的注解都会被@ComponentScan扫描到并添加到容器中

@Controller
@Repository
@Service
@Component

关于四个注解
@Component, @Service, @Controller, @Repository是spring注解,注解后可以被spring框架所扫描并注入到spring容器来进行管理
@Component是通用注解,其他三个注解是这个注解的拓展,并且具有了特定的功能
@Repository注解在持久层中,具有将数据库操作抛出的原生异常翻译转化为spring的持久层异常的功能。
@Controller层是spring-mvc的注解,具有将请求进行转发,重定向的功能。
@Service层是业务逻辑层注解,这个注解只是标注该类处于业务逻辑层。
用这些注解对应用进行分层之后,就能将请求处理,义务逻辑处理,数据库操作处理分离出来,为代码解耦,也方便了以后项目的维护和开发。

新建类 BookDao,BookService,BookController,并分别在类上加上
@Repository,@Service,@Controller

修改注解

import com.myspring.entity.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

// includeFilters 只包含
//excludeFilters 排除
 // FilterType.ANNOTATION 通过注解排除
@ComponentScan(value = "com.myspring")
@Configuration
public class MainConfig {

    // 声明一个Bean Id 为方法名
    @Bean
    public Person person(){
        return new Person("lisi",20);
    }


}

编写测试类

import com.myspring.configure.MainConfig;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Test02 {

    @Test
    public void Test1()
    {

        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
        String[] names = applicationContext.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }

    }

}

测试结果
mainConfig
bookController
bookDao
bookService

备注
// includeFilters 只包含
//excludeFilters 排除
// FilterType.ANNOTATION 通过注解排除
@ComponentScan(value = “com.myspring”,excludeFilters ={
@ComponentScan.Filter(type = FilterType.ANNOTATION,classes = {Controller.class,Service.class})
})

要使用includeFilters 时需添加useDfaultFilters = false;

猜你喜欢

转载自blog.csdn.net/qq_38637066/article/details/81837701