06.Spring中Bean自动装配

在Spring中,可以通过类的名称给引用对象赋值,使用该方法有如下注意:在该类中的引用值得属性的名称需要和引用的bean的id值一致;

比如StudentDao和StudentService ,在StudentService中创建StudentDao并且创建set方法,在配置文件中就可以使用byName注入;

自动装配的方式有如下五种,使用自动装配需要配置 元素的 autowire 属性。autowire 属性有五个值,具体说明如下表所示:

一、byName

1.创建实体类

@Datapublic class StudentService {    private StudentDao studentDao;    public void setUserDao(StudentDao studentDao) {        this.studentDao = studentDao;    }    public void login() {        studentDao.login();    }}
@Datapublic class StudentDao {    public void login() {        System.out.println("到了登录这里");    }}

2.配置文件中注入bean

3.执行测试

@Testpublic void testHello() {    //从类路径 ClassPath 中寻找指定的 XML 配置文件,    //找到并装载完成 ApplicationContext 的实例化工作    ApplicationContext context =            new ClassPathXmlApplicationContext("applicationContext.xml");    //根据ID得到实例化对象    StudentService studentService = context.getBean("studentService", StudentService.class);    //调用对象的方法    studentService.login();}

二、 byType

byType和byName类似,不过如果有多个相同类型的时候,byType会报错;

三、constructor

根据构造方法的参数的数据类型,进行 byType 模式的自动装配。

四、 autodetect

如果发现默认的构造方法,则用 constructor 模式,否则用 byType 模式。

五、 no

默认情况下,不使用自动装配,Bean 依赖必须通过 ref 元素定义。

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章