Java:
1.8
javaMaven:
3
springSpringFramework版本以及各组件成员:
5.1.1.RELEASE
ui
- spring-context
- spring-core
- spring-beans
@Required
注释适用于bean属性setter方法, 再经过在bean定义或经过自动装配一个明确的属性值:this
Required意为"须要", 它代表受影响的 bean 属性在配置时必须放在 XML 配置文件中,不然容器就会抛出一个 BeanInitializationException 异常。code
public class SimpleMovieLister { private MovieFinder movieFinder; @Required public void setMovieFinder(MovieFinder movieFinder) { this.movieFinder = movieFinder; } // ... }
@Required
将在之后的版本弃用.xml
TestBean.java
- 一个Bean(这不是一个规范的JavaBean, 顺口而叫的):blog
package noioo; import org.springframework.beans.factory.annotation.Required; public class TestBean { private String theValue; public String getTheValue() { return theValue; } @Required // 用在set上面 public void setTheValue(String theValue) { this.theValue = theValue; } }
在spring-beans.xml
中启用注解.get
<?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:content="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.xsd"> <content:annotation-config/> <bean id="testBean" class="noioo.TestBean"> <property name="theValue" value="Hello, World"/> </bean> </beans>
执行者 - Runner.java
it
package noioo; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Runner { public static void main(String[] args){ ApplicationContext context = new ClassPathXmlApplicationContext("spring-beans.xml"); TestBean testBean = (TestBean)context.getBean("testBean"); System.out.println(testBean.getTheValue()); } }
执行结果io
Hello, World Process finished with exit code 0