天天看点

[笔记] Spring IOC 基于注解方式

 什么是注解

  1. 注解是代码特殊标记,格式:​

    ​@注解名称(属性名称=属性值, 属性名称=属性值..)​

  2. 使用注解,注解作用在​

    ​类​

    ​​上面,​

    ​方法​

    ​​上面,​

    ​属性​

    ​上面
  3. 使用注解目的:​

    ​简化xml​

    ​配置

注解功能类似的注解,一共有四个:

  • @Component
  • @Repository
  • @Service
  • @Controller

这四个中,另外三个都是基于 @Component 做出来的,而且从目前的源码来看,功能也是一致的,那么为什么要搞三个呢?主要是为了在不同的类上面添加时方便。

  • 在 Service 层上,添加注解时,使用 @Service
  • 在 Dao 层,添加注解时,使用 @Repository
  • 在 Controller 层,添加注解时,使用 @Controller
  • 在其他组件上添加注解时,使用 @Component
@Service
public class UserService {
    public List<String> getAllUser() {
        List<String> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            users.add("javaboy:" + i);
        }
        return users;
    }
}      

XML 配置自动化扫描

<!--    扫描所有-->
    <context:component-scan base-package="cn.ch3nnn.springdemo"/>

    <!-- XML 配置中按照注解的类型进行扫描-->
    <context:component-scan base-package="cn.ch3nnn.springdemo" use-default-filters="false">
        <!--        注解类型包含Service 自动扫描-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
        <!--        注解类型不包含Controller 自动扫描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>      

Java 代码配置自动扫描

@Configuration
@ComponentScan(basePackages = "org.javaboy.javaconfig.service")
public class JavaConfig {
}      

对象注入实现属性注入

  1. @Autowired  根据属性类型进行自动装配
  2. @Resources  可以根据类型注入,也可以根据名称注入
  3. @Qualifier  根据名称进行注入,这个@Qualifier 注解的使用,和上面@Autowired 一起使用
  4. @Value:注入普通类型属性
@Value(value = "abc")
private String name