04 Spring 注解配置,简化xml配置,@Service、@Autowired简介

转载请注明来源 赖赖的博客

导语

简单的不一定是好的,复杂的也不一定是好的,合适的才是最好的。

通过增加Spring注解从而简化Xml配置,并提供实例。

建议先了解Spring ApplicationContext的xml配置方式。可参考03 Spring IoC之对象间的相互关系和 Spring 应用结构

实例

如果看过 03 Spring IoC之对象间的相互关系和 Spring 应用结构 可以跳到项目详解这一节,因为结构和输出结构与上一节一致。

项目工程目录结构和代码获取地址

获取地址(版本Log将会注明每一个版本对应的课程)

https://github.com/laiyijie/SpringLearning

目录结构

目录结构

运行工程

运行具有Main函数的 App.java
得到如下输出

false

工程简单分层(如果看过 03 Spring IoC之对象间的相互关系和 Spring 应用结构 可以略过到下一节)

现在工程有三个包,包之间的关系如下:

  • 应用层:me.laiyijie.demo , 只调用服务层
  • 服务层:me.laiyijie.demo.service,只调用数据层
  • 数据层:me.laiyijie.demo.dataaccess,最底层,直接操作持久化数据(文件、数据库等)

项目详解

从App.java入手

App.java(与上一节比无变化)

package me.laiyijie.demo;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import me.laiyijie.demo.service.UserService;

public class App {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("root-context.xml");
        
        UserService userService = context.getBean(UserService.class);
        
        System.out.println(userService.login("lailai", "laiyijie","127.0.0.1"));
        
        context.close();
    }
}

Main函数中依旧只有四行代码,这里引用到了UserService,并且调用了UserServicelogin方法。

我们来看下UserService

UserService.java(与上一节比无变化)

package me.laiyijie.demo.service;

public interface UserService{
    
    boolean login(String username,String password,String ip);
    
}

OK,非常简单,只是一个接口,定义了有这么一个方法,具体实现是在同一个包下面的另一个文件,UserServiceImpl.java中

UserServiceImpl.java(变化来了!)

package me.laiyijie.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.laiyijie.demo.dataaccess.AccountAccess;
import me.laiyijie.demo.dataaccess.LoginLogAccess;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private AccountAccess accountAccess;
    @Autowired
    private LoginLogAccess loginLogAccess;
    
    public boolean login(String username, String password,String ip) {
        
        if (!accountAccess.isAccountExist(username)) {
            return false;
        }
        
        if (accountAccess.isPasswordRight(username, password)) {
            accountAccess.updateLastLoginTime(username);
            loginLogAccess.addLoginLog(username, ip);
            return true;
        }
        return false;
    }
}

在这里新增了两个注解 @Service、@Autowired ,减少了getter和setter

  • @Service 在类前注释,将此类实例化,等同于在root-context中配置

      <bean class="me.laiyijie.demo.service.UserServiceImpl">
      </bean>
    
  • @Autowired 在属性前配置,将属性对应的对象从工厂中取出并注入到该bean中,等同于

      <property ref="accountAccessImpl" name="accountAccess"></property>
      <property ref="loginLogAccessImpl" name="loginLogAccess"></property>
    

两个注解组合起来等同于:

<bean class="me.laiyijie.demo.service.UserServiceImpl">
    <property ref="accountAccessImpl" name="accountAccess"></property>
    <property ref="loginLogAccessImpl" name="loginLogAccess"></property>
</bean>

那么,让我们看一下root-context.xml是否可以去除掉这一部分的配置!

root-context.xml(有变化)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    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-4.3.xsd">

    <bean id="accountAccessImpl" class="me.laiyijie.demo.dataaccess.AccountAccessImpl"></bean>
    <bean id="loginLogAccessImpl" class="me.laiyijie.demo.dataaccess.LoginLogAccessImpl"></bean>
    
    <context:component-scan base-package="me.laiyijie.demo.service"></context:component-scan>

</beans>

yes!你没看错,配置me.laiyijie.demo.service.UserServiceImpl这个bean的代码被两个注解代替了,而新增了一行:

<context:component-scan base-package="me.laiyijie.demo.service"></context:component-scan>

从文字直译就可以看出,这一行代表了

  • me.laiyijie.demo.service包下面扫描 componet

而@Service正是componet 中的一种

进一步简化

是否可以更进一步简化root-context.xml的配置?!因为还有两个bean是用xml配置的!!

当然可以,通过如下步骤

  1. 删除root-context.xml中的两行bean配置

  2. 在AccountAccessImpl.java和LoginLogAccess.java的类定义前增加@Service注解

  3. 修改root-context.xml 中componet-scan的 base-package属性为me.laiyijie.demo,如下所示

     <context:component-scan base-package="me.laiyijie.demo"></context:component-scan>
    

小结:

  1. @Service可以将一个类定义成一个bean(也就是实例化并放入工厂)
  2. @Autowired 可以根据属性的类型来注入工厂中存在的该类型的实例
  3. 要使用注解,需要在ApplicationContext中增加 <context:component-scan base-package="me.laiyijie.demo"></context:component-scan>配置
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,361评论 6 343
  • 来源:关于Spring IOC (DI-依赖注入)你需要知道的一切作者:zejian Dao层(AccountDa...
    杨井阅读 5,272评论 0 27
  • 上一篇:Spring学习笔记(四、Bean装配(上)) 这篇讲解Bean管理的注解实现及例子 主要内容有: Cla...
    鲁克巴克诗阅读 1,245评论 2 6
  • 为什么要搭建deb源 公司网络隔离, 有一部分服务器不允许链接外网 自己开发的安装程序需要统一管理 搭建步骤 在一...
    imsilence阅读 2,844评论 0 0