需要一些帮助来理解注解 - Spring 注解

2024-04-10

我正在尝试学习 Spring 和 Hibernate,并且我真的很难理解注释及其工作原理。我在互联网上看到的大多数示例都是基于注释的示例,因此我需要先了解注释如何工作,然后才能学习 Spring 或 Hibernate

我知道它们是什么以及它们的用途。我知道它们替换了 xml 配置。 IE。您可以使用注释直接在 Java 代码中配置 bean。我不明白的是如何使用它们以及何时可以使用它们。

试图了解如何做到这一点,我认为如果我看到两者之间的区别将会很有帮助。我这里有一个简单的 Spring 程序。如果我要将此示例程序转换为使用注释,我需要做什么?

我想这样做的原因是因为我在下面提供的程序是我非常理解的程序(我当前正在阅读的 Spring in Action 书中的一个示例)。如果将其转换为注释版本,我将了解如何以及在何处使用注释。

有什么建议么?

提前致谢


工具主义者.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean id="saxophone" class="com.sia.ch1.instrumentalist.Saxophone" />
    <bean id="piano" class="com.sia.ch1.instrumentalist.Piano" />

    <!--  Injecting into bean properties Ken 1 -->
    <bean id="kenny" class="com.sia.ch1.instrumentalist.Instrumentalist">
        <property name="song" value="Jingle Bells"/>
        <property name="instrument" ref="piano"/>       
    </bean> 
</beans>

器乐界面

package com.sia.ch1.instrumentalist;
public interface Instrument {
    void play();
}

器乐执行者

package com.sia.ch1.instrumentalist;

import com.sia.ch1.performer.PerformanceException;
import com.sia.ch1.performer.Performer;

public class Instrumentalist implements Performer{

    private Instrument instrument;
    private String song;

    public Instrumentalist(){}

    public void perform() throws PerformanceException{
        System.out.print("Playing " + song + " : ");        
        instrument.play();
    }

    public void setInstrument(Instrument instrument) {
        this.instrument = instrument;
    }   

    public void setSong(String song) {
        this.song = song;
    }   
}

乐器 - 钢琴

package com.sia.ch1.instrumentalist;

public class Piano implements Instrument{
    public Piano(){}
    public void play(){
        System.out.println("PLINK PLINK");
    }
}

乐器 - 萨克斯管

package com.sia.ch1.instrumentalist;

public class Saxophone implements Instrument{
    public Saxophone(){}
    public void play(){
        System.out.println("TOOT TOOT TOOT");
    }
}

主班

package com.sia.ch1.instrumentalist;

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.FileSystemXmlApplicationContext;

    import com.sia.ch1.performer.PerformanceException;
    import com.sia.ch1.performer.Performer;

    public class InstrumentalistApp {

        public static void main(String[] args){
            ApplicationContext ctx = new FileSystemXmlApplicationContext("c:\\projects\\test\\conf\\instrumentalist.xml");

            Performer performer = (Performer) ctx.getBean("kenny");

            try {
                performer.perform();            
            } catch (PerformanceException e) {
                e.printStackTrace();
            }
        }   
    }

例外

package com.sia.ch1.performer;

public class PerformanceException extends Exception {

    public PerformanceException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public PerformanceException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

    public PerformanceException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public PerformanceException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }
}

Edit 1

为了尝试转换上面的内容,我将通过这两个简单的例子:

Ex1: http://jroller.com/habuma/entry/reducing_xml_with_spring_2 http://jroller.com/habuma/entry/reducing_xml_with_spring_2

Ex2: http://www.theserverside.com/tutorial/Spring-Without-XML-The-Basics-of-Spring-Annotations-vs-Spring-XML-Files http://www.theserverside.com/tutorial/Spring-Without-XML-The-Basics-of-Spring-Annotations-vs-Spring-XML-Files

我有点理解第一个 URL 中的示例,但第二个 URL 让我有点困惑。在第二个 URL 的示例中,其目的是什么SummaryConfig班级?看起来好像SummaryConfigclass 是 XML 文件的 Java 版本。第一个示例中的示例中没有使用这种方法。两者有什么区别?

当您使用注释时,您是否可以将配置详细信息放在 Java 类中(例如SummaryConfig)并且您还可以将注释放在 bean 本身中,如第一个 URL 中的示例所示?

Thanks

Edit 2

这是我到目前为止所做的,

我修改了xml文档,删除了配置并启用了组件的自动扫描(注:我更改了修改版本的包名称)

<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-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:component-scan base-package="com.sia.ch1.instrumentalist.annotate" />

</beans>

向 Piano 和 Saxophone 类添加了 @Component 注释。我认为这告诉容器这个类应该包含在要自动扫描的类中。正确的?

package com.sia.ch1.instrumentalist.annotate;

import org.springframework.stereotype.Component;

@Component
public class Piano implements Instrument{

    public Piano(){}
    public void play(){
        System.out.println("PLINK PLINK");
    }
}

package com.sia.ch1.instrumentalist.annotate;

import org.springframework.stereotype.Component;

@Component
public class Saxophone implements Instrument{
    public Saxophone(){}
    public void play(){
        System.out.println("TOOT TOOT TOOT");
    }
}

这就是我陷入困境的地方(乐器演奏家类别)。

  • 这个类需要@Component注解吗?或者仅当该类要从另一个类引用时才需要?

  • 我知道我需要 @Autowire 乐器和歌曲属性,但我怎么知道我是否想按名称或按类型等自动连接

  • 如果在此类中没有代表 String 属性的 bean,我将如何自动装配 String 属性?即乐器属性将引用钢琴类,但是歌曲属性将使用什么自动装配?


package com.sia.ch1.instrumentalist.annotate;
//
    import org.springframework.stereotype.Component;
    import com.sia.ch1.performer.PerformanceException;
    import com.sia.ch1.performer.Performer;
    //
        @Component
        public class Instrumentalist implements Performer{

        private Instrument instrument;
        private String song;

        public Instrumentalist(){}

        public void perform() throws PerformanceException{
            System.out.print("Playing " + song + " : ");        
            instrument.play();
        }

        public void setInstrument(Instrument instrument) {
            this.instrument = instrument;
        }   

        public void setSong(String song) {
            this.song = song;
        }   
    }

我认为我是对的,任何其他类都不需要注释。

Thanks


这就是我陷入困境的地方(乐器演奏家类别)。

  • 这个类需要@Component注解吗?或者只是 如果要从另一个类引用该类,则需要?

是的,是的,如果您希望注释扫描为您从类创建 bean,而无需单独的 xml 配置。既然你要求Instrumentalist- 使用bean名称实现kenny(按名称,而不是按类型Instrumentalist)在你的主方法中,它也需要命名。

使用@Component、@Repository、@Controller 和@Service 注解的类是Spring 在配置ApplicationContext 时扫描的类。这四个注释之间的区别是语义上的(区分类在代码中的角色),它们都做完全相同的事情(除非您有一些仅处理某些注释类型的 AOP 东西;现在您不这样做不需要关心这个)。

使用任何上述注释来注释类与在 xml 中声明 bean 相同:

<bean id="saxophone" class="com.sia.ch1.instrumentalist.Saxophone"> ... </bean>

@Component
public class Saxophone implements Instrument{

请注意,默认情况下,bean 的命名与类相同,只是类名的第一个字母更改为小写(因此@Component public class SomeClass将创建一个名为“someClass”的 bean)。

如果你想命名你的 bean,你可以将名称作为注释的参数:

@Component("kenny")
public class Instrumentalist implements Performer {

 <bean id="kenny" class="com.sia.ch1.instrumentalist.Instrumentalist">

将参数提供给注释的另一种方法是使用@Component(value="kenny")。原因是value=-part 是可选的,因为注释的工作方式如下:如果只给出一个参数而不告诉字段名称,并且注释包含一个名为value,该参数将被设置为value-场地。如果字段名称是其他的,或者你想设置注释的多个字段,则需要显式定义字段:@SomeAnnotation(field1="some string", field2 = 100) or @SomeAnnotation(value="someValue", anotherField="something else")。这有点离题了,但了解一下还是有好处的,因为一开始可能会令人困惑。

因此,@Component 注释告诉 Spring 上下文您想要创建一个 bean(或多个 bean,请参阅@Scope http://static.springsource.org/spring/docs/3.0.x/javadoc-api/)来自带注释的类。当没有@Scope http://static.springsource.org/spring/docs/3.0.x/javadoc-api/-注释集,默认情况下,bean 将被创建为单例(您可以将 bean 自动装配到多个类,但它们都看到相同的单个实例)。有关不同范围的更多信息,我建议阅读官方文档 http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes.

  • 我知道我需要 @Autowire 乐器和歌曲属性
    但我怎么知道我是否想按名称或按类型等自动装配

通常,如果您只有一个类型(接口)的单个实现,则按类型自动装配会更方便。当只有一个实现时,按类型自动装配是有效的,否则 Spring 无法决定实例化和注入哪个实现。

在你的例子中,你有两个不同的类来实现Instrument-界面:Saxophone and Piano。如果您尝试通过键入自动装配Instrument- 的领域Instrumentalist,当Spring构建时你会得到一个异常Instrumentalist-bean:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.sia.ch1.instrumentalist.annotate.Instrument] is defined: expected single matching bean but found 2: [piano, saxophone]

由于有两个Instrument- 实现,Spring没有足够的信息来确定你想要注入哪一个Instrumentalist。这就是@预选赛 http://static.springsource.org/spring/docs/3.0.x/javadoc-api/-annotation 介入。使用 @Qualifier,您可以告诉 Spring 注入自动装配的依赖项by-name。要注入Piano-实施Instrument在中使用@QualifierInstrumentalist是由以下人员完成的:

@Component(value="kenny")
public class Instrumentalist implements Performer
{
    @Autowired
    @Qualifier("piano")
    private Instrument instrument;

<bean id="kenny" class="com.sia.ch1.instrumentalist.Instrumentalist">
    <property name="instrument" ref="piano"/>       
</bean>

请注意,没有必要(但如果您愿意的话也可以)使用@Component("piano") in the Piano-class,因为默认命名将类的第一个字母更改为小写,然后将其用作 bean 名称。

  • 如果在这个类中没有 bean,我将如何自动装配 String 属性 代表它?即,乐器属性将引用钢琴类,但是歌曲属性将使用什么自动装配?

这是用注释画线的地方(据我所知);您不能使用注释声明 String 类型的 bean(因为 java.lang.String 不是接口,因此无法扩展,因为它是最终的并且没有接口)。然而,使用 xml 配置这是可能的:

<bean id="songName" class="java.lang.String">   
    <constructor-arg value="Valley of the Queens"/>
</bean>

您可以混合搭配 XML 和注释,并从注释引用 xml 中声明的 bean,反之亦然,将此 bean 注入到Instrumentalists' song-field:

@Autowired
@Qualifier("songName")
private String song;

希望这可以帮助您总体了解 Springs 的注释并开始使用,我仍然强烈建议您阅读官方文档,因为还有很多内容。如果您更喜欢阅读书籍而不是屏幕,我建议例如Apppress 的春季食谱 http://www.apress.com/9781430224990(但我确信还有很多其他好书)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

需要一些帮助来理解注解 - Spring 注解 的相关文章

随机推荐

  • 在 Windows 7 上找不到模块“连接”

    请看下面 C Program Files nodejs gt npm g install connect npm http GET https registry npmjs org connect npm http GET https re
  • React Native + React Native Paper 应用程序中未显示图标

    这是一个新鲜的React Native应用程序使用React Native Paper 我按照以下说明进行操作https callstack github io react native paper getting started html
  • 无法实现 grunt-connect-proxy

    为了 http 127 0 0 1 9000 我得到的路线 不能获取 对于 v1 路线我得到 未找到 在此服务器上找不到请求的 URL v1 这是我的 Gruntfile js Generated on 2013 10 08 using g
  • 计算小于当前值的值的数量

    我想计算列中的行数input如果值小于当前行 请参阅下面想要的结果 对我来说 问题是条件基于当前行值 因此它与条件是固定数字的一般情况有很大不同 data lt data frame input c 1 1 1 1 2 2 3 5 5 5
  • 绑定这个更好还是使用变量更好? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • C# 无法从传输连接读取数据:现有连接被远程主机强制关闭。读取网络流

    我看过 无法从传输连接读取数据连接已关闭 https stackoverflow com questions 26995191 unable to read data from the transport connection the co
  • JavaFX 场景的显示随机延迟

    我创建了一个 JavaFX 应用程序 在 Ubuntu Java SE 运行时环境 版本 1 8 0 131 b11 上运行 并制作了一个简单的测试应用程序 public class DelayedSceneApplication exte
  • Angular 2 模拟响应不起作用

    我有以下 Angular 2 测试 tslint disable no unused variable import provide from angular core import MockBackend from angular htt
  • Pyinstaller 无法执行脚本 pyi_rth_pkgres

    I converted the py script to exe using pyinstaller but when I try to run the exe I got this How can I fix it 您必须告诉 pyins
  • 从文件express js 提供 json

    新手要表达的是 我有一个包含 db json 文件的文件夹 并且每 11 秒就会被新的 db json 替换 让express js 提供服务以便在 api 调用上显示新内容的最佳方法是什么 这是我到目前为止所拥有的 const expre
  • 具有多重身份的B2C用户

    在 Azure B2C 中 有多个身份提供商 在本示例中 我将使用本地帐户和 Google 帐户 新用户使用电子邮件地址注册本地帐户 电子邮件受保护 cdn cgi l email protection 他们使用该网站 下次返回时 他们决定
  • Lucene 中跨多个字段的重复值的影响

    在 lucene 索引中的多个字段中重新索引相同的值会产生什么影响 这个想法是 某人的名字是他们的名字和一般详细信息的一部分 所以我想将该值索引到多个字段中 Ted Bloggs 我可能会索引如下 Field Value firstName
  • 删除 SQLPLUS 中不需要的/额外的数据

    我正在通过批处理文件运行一个文件 批处理文件 sqlplus admin admin SERVER abc sql gt output txt SQL 文件 abc sql set PAGESIZE 1000 set LINESIZE 55
  • Symfony POST 变量始终为空

    这是我的 Symfony 控制器 class MyPageController extends Controller public function indexAction Request request postData request
  • 如何使用“setInterval()”每秒更新时间而不使时间每秒闪烁?

    我正在使用一个下拉列表 该列表使用时刻时区显示不同的时区 例如 当您单击标有 est 的下拉列表时 它将显示东部时间的时间 当您单击 cst 时 将显示 cst 时间 依此类推 无论如何 我遇到的问题是 我使用setInterval upd
  • Magento:设置集合限制

    我试图找出的问题是如何对集合设置限制 我在 Google 上找到的答案仅适用于具有 setPage pageNum pageSize 的目录 这对任何其他集合都不起作用 请参阅下面的答案 做这件事有很多种方法 collection Mage
  • 记录执行的java代码的行数

    我正在编写 PHP Web 应用程序的一部分 将在高中错误查找竞赛中使用 用户必须在给定的 Java 程序中查找错误 作为其中的一部分 当 Java 程序执行时 我们希望突出显示已执行代码的 Java 程序源代码行 为此 我们需要的是已执行
  • Google Cloud 上的一个项目下是否可以拥有多个聊天机器人

    最近 我用 DialogFlow 构建聊天机器人的项目空间用完了 我不认为我在 Google Cloud 上的项目中使用了最佳标准 任何提示都很棒 而且由于我尝试创建一个新的聊天机器人 它会告诉我项目空间不足 是否可以将这些聊天机器人放在同
  • 如何从匹配的几何效果中删除/控制淡入淡出效果?

    我有一个测试代码来显示这个问题 当我使用matchedGeometryEffect时 matchedGeometryEffect向渲染结果添加了不希望的淡入淡出效果 所以我喜欢删除这种淡入淡出效果甚至控制它 当我将视图颜色从一种颜色更改为另
  • 需要一些帮助来理解注解 - Spring 注解

    我正在尝试学习 Spring 和 Hibernate 并且我真的很难理解注释及其工作原理 我在互联网上看到的大多数示例都是基于注释的示例 因此我需要先了解注释如何工作 然后才能学习 Spring 或 Hibernate 我知道它们是什么以及