zoukankan      html  css  js  c++  java
  • Spring注解与否

    引入Spring注解的原因:

     传统的Spring做法是使用.xml文件来对bean进行注入或者是配置AOP、实物,这么做有两个缺点:

    1、如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大;如果按需求分开.xml文件,那么.xml文件又会非常多。总之这将导致配置文件的可读性与可维护性变得很低。

    2、在开发中.java文件和.xml文件之间不断切换,是一件麻烦的事,同时这种思维上的不连贯也会降低开发的效率。

      为了解决这两个问题,Spring引入了注解,通过“@XXX”的方式,让注解与Java Bean紧密结合,既大大减少了配置文件的体积,又增加了Java Bean的可读性与内聚性。

      以下是不使用注释的例子:

      

      以上是不使用注释的情况。其实可以看出很麻烦,什么都要装配在xml文件中。

    下面我们看一下使用注释的情况:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans
     3     xmlns="http://www.springframework.org/schema/beans"
     4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     5     xmlns:p="http://www.springframework.org/schema/p"
     6     xmlns:context="http://www.springframework.org/schema/context"
     7     xsi:schemaLocation="http://www.springframework.org/schema/beans
     8     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     9     http://www.springframework.org/schema/context
    10     http://www.springframework.org/schema/context/spring-context-3.0.xsd
    11     ">
    12     
    13     <context:component-scan base-package="com.spring"/>
    14     
    15     <bean id="zoo" class="com.spring.model.Zoo" />
    16     <bean id="tiger" class="com.spring.model.Tiger" />
    17     <bean id="monkey" class="com.spring.model.Monkey" />
    18 
    19 </beans>
    View Code

      注意第13行,使用必须告诉spring一下我要使用注解了,<context:component-scan base-package="XXX"/>是一种简单的,spring会自动扫描xxx路径下的注解。

      看到第15行,原来zoo里面应当注入两个属性tigger、monkey,现在不需要注入了。再看下,Zoo.java也很方便,把getter/setter都可以去掉:

    package com.spring.model;
    import org.springframework.beans.factory.annotation.Autowired;
    
    public class Zoo{
        @Autowired
        private Tiger tiger;
    
        @Autowired
        private Monkey monkey;
    
        public String toString(){
            return tiger+"
    "+monkey;
        }
         
    }

      这里@Autowired注解的意思就是,当Spring发现@Autowired注解时,将自动在代码上下文中找到和其匹配(默认是类型匹配)的Bean,并自动注入到相应的地方去。

    这里先说到这里,现在就知道为什么要用注释了。

    本文有节选自:https://www.cnblogs.com/xianfengzhike/p/9096824.html

  • 相关阅读:
    Codeforces 834D The Bakery
    hdu 1394 Minimum Inversion Number
    Codeforces 837E Vasya's Function
    Codeforces 837D Round Subset
    Codeforces 825E Minimal Labels
    Codeforces 437D The Child and Zoo
    Codeforces 822D My pretty girl Noora
    Codeforces 799D Field expansion
    Codeforces 438D The Child and Sequence
    Codeforces Round #427 (Div. 2) Problem D Palindromic characteristics (Codeforces 835D)
  • 原文地址:https://www.cnblogs.com/fzzzjjj/p/11407569.html
Copyright © 2011-2022 走看看