zoukankan      html  css  js  c++  java
  • @Autowired注解的使用

    使用Spring时,通过Spring注入的Bean一般都被定义成private,并且要有getter和setter方法,显得比较繁琐,增加了代码量,而且有时会搞忘造成错误。

    可以使用@Autowired注解来减少代码量。首先,在applicationContext中加入:

    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

    Spring使用这个BeanPostProcessor解析@Autowired注解。

    然后,在变量上添加@Autowired注解,并去掉相应的getter和setter方法:

    package com.school.service;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    
    import com.school.dao.ClasDAO;
    import com.school.entity.Clas;
    
    public class ClasServiceImpl implements ClasService{
        
        @Autowired
        private ClasDAO clasDAO;
        
      ...
        
    }

    并且在applicationContext中将相应的<property></property>标签去掉:

        <bean id="clasService" class="com.school.service.ClasServiceImpl">
        </bean> 

    Spring启动时,AutowiredAnnotationBeanPostProcessor会扫描所有的Bean,当发现其中有@Autowired注解时,就会找相应类型的Bean,并且实现注入。

  • 相关阅读:
    CentOS安装docker-compose
    CentOS安装docker
    CentOS7安装Python3.7
    Windows 10 任务栏添加网易云音乐控制按钮
    学习postman教程
    接口自动化测试理论
    【测试基础】界面测试
    CentOS7设置开机自启动方式
    CentOS7 安装Jenkins
    CentOS7使用docker搭建Solo博客
  • 原文地址:https://www.cnblogs.com/mstk/p/6213867.html
Copyright © 2011-2022 走看看