spring基于注解的 IOC 配置

用于创建对象的:相当于<bean id="" class="">
  @Component

    作用:
      把资源让 spring 来管理。相当于在 xml 中配置一个 bean。
    属性:
      value:指定 bean 的 id。如果不指定 value 属性,默认 bean 的 id 是当前类的类名,首字母小写。

  @Controller @Service @Repository

    三个注解都是针对 @Component 的衍生注解,他们的作用及属性都是一模一样的,只不过是提供了更加明确的语义化。
      @Controller :一般用于表现层的注解。
      @Service :一般用于业务层的注解。
      @Repository :一般用于持久层的注解。
    细节:如果注解中有且只有一个属性要赋值时 ,且名称是 value ,value 在赋值时可以不写。

用于注入数据的:相当于<property name="" ref="">  <property name="" value="">

  @Autowired

    作用:
      自动按照类型注入,当使用注解注入属性时,set方法可以省略,它只能注入其他 bean 类型。当有多个类型匹配时,
      使用要注入的对象变量名称作为 bean 的 id,在 spring 容器查找,找到了也可以注入成功,找不到就报错。
  @Qualifier

    作用:
      在自动按照类型注入的基础之上,再按照 Bean 的 id 注入。它在给字段注入时不能独立使用,必须和 @Autowire 一起使用;
      但是给方法参数注入时(使用构造函数注入数据时,给构造函数的参数使用),可以独立使用。
    属性:
      value:指定 bean 的 id。

  @Resource

    作用:
      直接按照 Bean 的 id 注入。它也只能注入其他 bean 类型。
    属性:
      name:指定 bean 的 id。

  @Value

    作用:
      注入基本数据类型和 String 类型数据
    属性:
      value:用于指定值

  集合类型的注入只能通过 xml 来实现

用于改变作用范围的:相当于<bean id="" class="" scope="">

  @Scope

    作用:
      指定 bean 的作用范围。
    属性:
      value:指定范围的值。
      取值:singleton prototype request session globalsession

和生命周期相关的:相当于<bean id="" class="" init-method="" destroy-method="" />

  @PostConstruct

    作用:
      用于指定初始化方法。

  @PreDestroy

    作用:
      用于指定销毁方法。

示例:

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    public UserServiceImpl() {
        System.out.println("service创建对象了");
    }

    @Override
    public void saveUser() {
        System.out.println("service保存用户");
        userDao.saveUser();
    }
}
@Repository("userDao")
public class UserDaoImpl implements UserDao {

    public UserDaoImpl() {
        System.out.println("dao对象创建了");
    }

    @Override
    public void saveUser() {
        System.out.println("dao保存用户");
    }
}

  注意:当使用注解注入时,set 方法不用写

创建 spring 的 xml 配置文件并开启对注解的支持:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  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">
  <!-- 告知 spring 创建容器时要扫描的包 -->
  <context:component-scan base-package="com.fgy"></context:component-scan>
</beans>

  注意:基于注解整合时,导入约束时需要多导入一个 context 名称空间下的约束。

猜你喜欢

转载自www.cnblogs.com/roadlandscape/p/12301103.html