Java 注解配置元信息
@Autowired 只按照byType 注入,由Spring提供
@Resource 默认按byName自动注入,也提供按照byType 注入,由JDK提供
// @Inject 需要依赖 <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency>
package com.rumenz; public class Holder { private Rumenz rumenz; public Holder(Rumenz rumenz) { this.rumenz = rumenz; } public Rumenz getRumenz() { return rumenz; } public void setRumenz(Rumenz rumenz) { this.rumenz = rumenz; } }
package com.rumenz; public class Rumenz { private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
<?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:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd"> <bean id="rumenz" class="com.rumenz.Rumenz"> <property name="id" value="123"/> <property name="name" value="入门小站"/> </bean> </beans>
package com.rumenz; public class DemoApplication { @Autowired private Holder holder; @Resource private Holder holder1; @Inject private Holder holder2; public static void main(String[] args) { AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext(); XmlBeanDefinitionReader xr=new XmlBeanDefinitionReader(ac); xr.loadBeanDefinitions("Beans.xml"); ac.register(DemoApplication.class); ac.refresh(); DemoApplication bean = ac.getBean(DemoApplication.class); System.out.println(bean.holder.getRumenz().getName()); System.out.println(bean.holder1.getRumenz().getName()); System.out.println(bean.holder2.getRumenz().getName()); ac.close(); } @Bean public Holder holder(Rumenz rumenz){ return new Holder(rumenz); } }
入门小站 入门小站 入门小站