Spring学習(2)——IOCコメント

3202 ワード

@注記の方式
@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注記アプリケーションContext中東のと同等に、注記するクラスに使用されます.
@Service("bean名")は、アプリケーションContext中東のに等しい
2.@Resource注記はに等しい
注記のプロパティはクラスで、そのクラスで注記@resourceはアセンブリ関係を表します.
それは最後にアプリケーションContextでcontext:component-scanスキャンパッケージを使用し、