在Spring中,提供两种方式来让Spring IoC容器发现Bean。
(1)组件扫描
注解@Component代表Spring IOC会把这个类扫描生成Bean实例,而其中的value属性代表这个类在Spring中的ID,这就相当于XML方式定义的Bean的id。
通过定义资源的方式,让Spring IoC容器扫描对应的包,从而把Bean装配进来。
<context:component-scan base-package="com.shw"></context:component-scan>
注解@Resource默认按照Bean实例名称进行装配,@Resource包括name和type两个属性。name属性解析为Bean实例的名称,type属性解析为Bean实例的类型。
一、配置spring配置文件
<?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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.shw"></context:component-scan>
</beans>
二、创建相关类
User类
package com.shw;
import org.springframework.stereotype.Component;
@Component(value="user") //组件扫描装配Bean
public class User {
public void show(){
System.out.println("User.show() ........");
}
}
Manger类
package com.shw;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component(value="manger") //组件扫描装配Bean
public class Manger {
@Resource(name="user") //按照Bean实例名进行装配
private User us;
@Value("管理员") //值注入
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("Manger.show() ........");
us.show();
}
}
测试类
package com.shw;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
//加载applicationContext.xml
ApplicationContext context=new ClassPathXmlApplicationContext("spring-cfg.xml");
//获取实例
Manger manger=(Manger) context.getBean("manger");
//调用方法
manger.show();
System.out.println(manger.getName());
}
}
运行效果:
(2)自动装配:通过注解定义,使得一些依赖关系可以通过注解完成。
注解@Autowired默认按照Bean类型进行装配
修改Manger类的User类型属性us为自动装配
package com.shw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component(value="manger") //组件扫描装配Bean
public class Manger {
@Autowired //按照Bean类型进行装配
private User us;
@Value("管理员") //值注入
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("Manger.show() ........");
us.show();
}
}
运行结果: