3.笔记JAVA框架学习——Bean引用其他Bean

来源:互联网 发布:天津网络送花 编辑:程序博客网 时间:2024/05/21 10:18

3.笔记JAVA框架学习——Bean引用其他Bean

 

在配置Bean的时候,其实一直没说明什么是Bean,这样做是不对的。

在此处补齐。

bean

JavaBean是描述Java的软件组件模型,有点类似于Microsoft的COM组件概念。在Java模型中,通过JavaBean可以无限扩充Java程序的功能,通过JavaBean的组合可以快速的生成新的应用程序。对于程序员来说,最好的一点就是JavaBean可以实现代码的重复利用,另外对于程序的易维护性等等也有很重大的意义。

JavaBean 是一种JAVA语言写成的可重用组件。为写成JavaBean,类必须是具体的和公共的,并且具有无参数的构造器。JavaBean 通过提供符合一致性设计模式的公共方法将内部域暴露成员属性,set和get方法获取。众所周知,属性名称符合这种模式,其他Java 类可以通过自省机制发现和操作这些JavaBean 的属性。

配置 bean

l  配置形式:基于 XML 文件的方式;基于注解的方式

l  Bean 的配置方式:通过全类名(反射)、通过工厂方法(静态工厂方法 & 实例工厂方法)、FactoryBean

l  IOC 容器 BeanFactory & ApplicationContext 概述

l  依赖注入的方式:属性注入;构造器注入

l  注入属性值细节

l  自动转配

l  bean 之间的关系:继承;依赖

l  bean 的作用域:singleton;prototype;WEB 环境作用域

l  使用外部属性文件

l  spEL

l  IOC 容器中 Bean 的生命周期

l  Spring 4.x 新特性:泛型依赖注入

字面值

l  字面值:可用字符串表示的值,可以通过 <value> 元素标签或 value 属性进行注入。

l  基本数据类型及其封装类、String等类型都可以采取字面值注入的方式

l  若字面值中包含特殊字符,可以使用 <![CDATA[]]> 把字面值包裹起来。

引用其它 Bean

在上篇基础上,新增Dao.java文件如下:

publicclass Dao {

 

      private StringdataSource;

     

      public Dao(StringdataSource) {

            super();

            this.dataSource = dataSource;

      }

 

      publicvoidsetDataSource(StringdataSource) {

            this.dataSource = dataSource;

      }

     

      publicvoid save(){

            System.out.println("save by " + dataSource);

      }

     

      public Dao() {

            System.out.println("Dao's Constructor...");

      }

     

}

增加Service.java如下:

publicclass Service {

 

      private Daodao;

     

      publicvoid setDao(Daodao) {

            this.dao = dao;

      }

     

      public Dao getDao(){

            returndao;

      }

     

      publicvoid save(){

            System.out.println("Service's save");

            dao.save();

      }

     

}

在app.xml中增加配置如下:

      <!-- 配置 bean -->

      <beanid="dao5"class="Dao">

      <constructor-argvalue="testDao"></constructor-arg>

     

      </bean>

 

      <beanid="service"class="Service">

            <!-- 通过ref 属性值指定当前属性指向哪一个 bean! -->

            <propertyname="dao"ref="dao5"></property>

      </bean>

此外,main.java如下:

import org.springframework.context.ApplicationContext;

importorg.springframework.context.support.ClassPathXmlApplicationContext;

publicclass Main {

            publicstaticvoid main(String[]args) {

            //1.创建Spring IOC容器

            ApplicationContextapx =newClassPathXmlApplicationContext("app.xml");

            Service service = (Service)apx.getBean("service");

            System.out.println(service);

            service.save();

           

      }

     

}

执行如下:

Hello:Jerry

Service@3a5ed7a6

Service'ssave

saveby testDao

 

 

 

 

阅读全文
0 0