spring学习(2)——IOC注解

@注解的方式

@Service("userbean")
public class UserBean {
	@Resource(name="enHelloBean")
	private HelloBean bean;
	public void show(){
		System.out.println("show hello message...");
		bean.sayHello();
	}
	public static void main(String[] args) {
		new UserBean().show();
	}
	public HelloBean getBean() {
		return bean;
	}
	public void setBean(HelloBean bean) {
		this.bean = bean;
	}

}
@Service
public class EnHelloBean implements HelloBean {

	@Override
	public void sayHello() {
		System.out.println("Hello world!");
	}

}
<?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.2.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.2.xsd">
	
	<context:component-scan base-package="mychebao.demo5"></context:component-scan>
</beans>

xml注入方式

public class UserBean {
	@Resource(name="enHelloBean")
	private HelloBean bean;
	public void show(){
		System.out.println("show hello message...");
		bean.sayHello();
	}
	public static void main(String[] args) {
		new UserBean().show();
	}
	public HelloBean getBean() {
		return bean;
	}
	public void setBean(HelloBean bean) {
		this.bean = bean;
	}

}
public class EnHelloBean implements HelloBean {

	@Override
	public void sayHello() {
		System.out.println("Hello world!");
	}

}
<?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.2.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.2.xsd">
	
	
	<bean id="userbean" class="mychebao.demo5.UserBean">
		<property name="hello" ref="enhellobean"></property>
	</bean>
	<bean id="enhellobean" class="mychebao.demo5.EnHelloBean"></bean>
	
</beans>

总结:

1. @Service注解用于要注解的类,等同于applicationContext中东的<bean></bean>

@Service("bean名称"),等同于applicationContext中东的<bean id="bean名称"></bean>

2. @Resource注解等同于<bean><property></property></bean>

注解的属性是一个类,在那个类注解@resource表示装配关系

那么等同于<bean><property ref=""> </property></bean>

如果注解resource的属性类,含有多个实现类,并且都有注解Service

那么可以在@resource(name="")来指定和注解Service的一一装配关系

最后在applicationContext中使用context:component-scan扫描包,不使用<bean id="">去一一对应

还是推荐直接使用简单的@Resource

3. 使用注入的方式,必须要扫描组件,既context:component-scan

4.    建议使用xml的方式注入,因为这样的方式比较清晰明了

你可能感兴趣的:(spring学习(2)——IOC注解)