当前位置:K88软件开发文章中心编程语言JavaSpring → 文章内容

Spring @Autowired 注释

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-15 16:20:53

ctory.annotation.Autowired;public class TextEditor { private SpellChecker spellChecker; @Autowired public TextEditor(SpellChecker spellChecker){ System.out.println("Inside TextEditor constructor." ); this.spellChecker = spellChecker; } public void spellCheck(){ spellChecker.checkSpelling(); }}下面是配置文件 Beans.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-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config/> <!-- Definition for textEditor bean without constructor-arg --> <bean id="textEditor" class="com.tutorialspoint.TextEditor"> </bean> <!-- Definition for spellChecker bean --> <bean id="spellChecker" class="com.tutorialspoint.SpellChecker"> </bean></beans>一旦你在源文件和 bean 配置文件中完成了上面两处改变,让我们运行一下应用程序。如果你的应用程序一切都正常的话,这将会输出以下消息:Inside SpellChecker constructor.Inside TextEditor constructor.Inside checkSpelling.@Autowired 的(required=false)选项默认情况下,@Autowired 注释意味着依赖是必须的,它类似于 @Required 注释,然而,你可以使用 @Autowired 的 (required=false) 选项关闭默认行为。即使你不为 age 属性传递任何参数,下面的示例也会成功运行,但是对于 name 属性则需要一个参数。你可以自己尝试一下这个示例,因为除了只有 Student.java 文件被修改以外,它和 @Required 注释示例是相似的。package com.tutorialspoint;import org.springframework.beans.factory.annotation.Autowired;public class Student { private Integer age; private String name; @Autowired(required=false) public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } @Autowired public void setName(String name) { this.name = name; } public String getName() { return name; }}

上一页  [1] [2] 


Spring @Autowired 注释