注解方式实例化Java类

context:component-scan标签

  Sprng容器通过context:component-scan标签扫描其base-package标签属性值指定的包及其子包内的所有的类并实例化被@Component、@Repository、@Service或@Controller等注解所修饰的类。

  @Component:基本注解

  @Respository:持久层(一般为dao层)注解

  @Service:服务层或业务层(一般为service层)注解

  @Controller:控制层(一般为controller层)注解

  默认情况下Spring依据默认命名策略为通过注解实例化的对象命名:类名第一个字母小写. 也可以在注解中通过@Component、@Repository、@Service或@Controller注解的value属性标识名称。

bean内属性赋值

Sprng容器通过context:component-scan标签扫描时还会自动实例化AutowiredAnnotationBeanPostProcessor 类, 该实例对象可以自动装配具有 @Autowired 和 @Resource 或@Inject注解的属性。

@Autowired

1、成员变量(不考虑访问权限)、构造函数或setter方法都可以使用@Autowired注解

2、默认情况下@Autowired 注解依据类型自动为成员变量赋值,当 IOC 容器里存在多个类型相同的 Bean 对象时就会依据成员变量名进行赋值,此时要求变量名必须是多个Bean对象中的一个,否则就会出现异常, 该异常可以通过在 @Qualifier 注解指定实例名的方式解决;

3、默认情况下,通过@Authwired 注解为成员变量赋值时,如果Spring 找不到匹配的 Bean为成员变量赋值则会抛出异常;如果该成员变量允许不被设置, 可以设置 @Authwired 注解的 required 属性为 false;

操作如下所示:

//创建一个类
package com.zzj.vo;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

//使用Component基本注解
@Component
public class School {

    //bean内属性赋值
    @Autowired
  //从多个实现类中选择需要的,如果不加当有多个实现类时会报错 @Qualifier(
"b") private Date birth; public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } }
<!--application.xml-->
<bean id="b" class="java.util.Date"></bean>
<bean id="p" class="java.util.Date"></bean>
<!--Spring扫描com.zzj.vo包中Date类,由于该类使用了@Component注解,所以该类被实例化-->
<context:component-scan base-package="com.zzj.vo"></context:component-scan>
//测试类
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
System.out.println(context.getBean(School.class).getBirth());

注意:

  1、使用context:component-scan标签需要添加spring-aop-4.3.10.RELEASE.jar包

  2、base-package标签属性属性值:

    a、Spring 容器将会扫描该属性值指定包及其子包中的所有类;

    b、该属性值支持*通配符,例如“com.lq.*.imp”表示扫描诸如com.lq.book.imp包及其子包中的类;

    c、当需要扫描多个包时, 使用逗号分隔;

    d、resource-pattern标签属性可以指定Spring容器仅扫描特定的类而非基包下的所有类,比如resource-pattern="/*.class"表示只扫描基包下的类,基包的子包不会被扫描。

context:component-scan子标签:

  1、<context:include-filter> 子标签设定Spring容器扫描时仅扫描哪些expression指定的类,该子标签需要和context:component-scan父标签中的use-default-filters属性一起使用;

  2、<context:exclude-filter>子标签设定Spring容器扫描时不扫描哪些expression指定的类;

<context:component-scan base-package="com.zzj.vo">
    <context:exclude-filter type="annotation" expression=""/>
    <context:include-filter type="annotation" expression=""/>
</context:component-scan>
原文地址:https://www.cnblogs.com/yimengxianzhi/p/12158840.html