Spring学习笔记之bean的基础知识

 更新时间:2017年12月13日 10:53:37   作者:小崔  
ean在Spring和SpringMVC中无所不在,将这个概念内化很重要,所以下面这篇文章主要给大家介绍了关于Spring学习笔记之bean基础的相关资料,文中通过示例代码介绍的非常详解,需要的朋友可以参考下。

Bean:

  • 在Spring技术中是基于组件的
  • 最基本了是最常用的单元
  • 其实实例保存在Spring的容器当中

Bean通常被定义在配置文件当中,Bean实例化由Spring的Ioc容器进行管理,Bean的实例可以通过Beanfactory进行访问,实际上大部分J2EE应用,Bean是通过ApplicationContext来访问的,ApplicationContext是BeanFactory的子接口,功能要比BeanFactory强大许多

在前面得博客依赖注入与控制反转中演示了应用spring实现ioc,在ApplicationContext.xml中有bean的配置,里面只是bean简单的应用。这篇主要是进一步学习使用bean。

一、定义

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="DaoImpl" class="Cuiyw.Spring.Dao.DaoImpl"></bean>
<bean id="ServiceImpl" class="Cuiyw.Spring.Service.ServiceImpl" scope="singleton">
<property name="dao" ref="DaoImpl"></property>
</bean>
</beans>

上面的代码是之前博客配置的,可以看到bean的基本构成。 <beans/>是Sring配置文件的根节点,一个<beans/>节点里面可以有多个<bean>节点。在bean中常用两个属性:ID,Class. ID是一唯一标识,来确定是哪个bean,可以让其他bean中使用id引用。class用来指定是哪个class。同时还可以设置scope属性,scope有两种:singleton,non-singelton。singleton:单实例模式(默认,构造方法为private),整个Spring的容器中只有一个共享实例存在(singleton)。non-singelton:每次请求该bean,Spring容器都会新建立一个bean实例,然后返回给程序(request,session,prototype)。

二、创建

Bean的命名机制

id 当在Spring的窗口当中,查找某个Bean对象时,首先根据id进行查找,将其余作为Bean的默认名称,如果ID属性不存在,则根据Name属性进行查找(将其中的第一个名称作为默认的名称),如果ID和NAME都不存在根据类的名称进行查找。id---------->name--------------->类名。

Bean的别名:可以使用alias来为bean指定别名.

下面的配置文件还是在上面的xml基础上修改的。这里配置了ID为ServiceImpl的bean设置了别名。我们可以使用它的name、id、alias来获取service。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="DaoImpl" class="Cuiyw.Spring.Dao.DaoImpl"></bean>
<bean id="ServiceImpl" class="Cuiyw.Spring.Service.ServiceImpl" scope="singleton" name="ServiceA">
<property name="dao" ref="DaoImpl"></property>
</bean>
<alias name="ServiceA" alias="ServiceA1"/>
</beans>
package Cuiyw.SpringAop;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import Cuiyw.Spring.IService.IService;
public class App 
{
 public static void main( String[] args )
 {
 ApplicationContext context=new ClassPathXmlApplicationContext(new String[]{"ApplicationContext.xml"});
 BeanFactory factory=context;
 IService service=(IService)factory.getBean("ServiceA1");
 service.service("Cuiyw ServiceA1"); 
 service=(IService)factory.getBean("ServiceA");
 service.service("Cuiyw ServiceA"); 
 service=(IService)factory.getBean("ServiceImpl");
 service.service("Cuiyw ServiceImpl"); 
 }
}


三、注入

1.基本类型和string

可以使用value元素来设置,在上面的代码基础上稍作修改

<property name="baseProperty" value="222"></property>
package Cuiyw.Spring.Service;
import Cuiyw.Spring.IDao.IDao;
import Cuiyw.Spring.IService.IService;
public class ServiceImpl implements IService{
 private IDao dao;
 private int baseProperty;
 public IDao getDao() {
  return dao;
 }
 public void setDao(IDao dao) {
  this.dao = dao;
 }
 public void service(String name) {
  System.out.println(dao.sayHello(name)+" baseProperty:"+getBaseProperty());
 }
 public int getBaseProperty() {
  return baseProperty;
 }
 public void setBaseProperty(int baseProperty) {
  this.baseProperty = baseProperty;
 }
}


对于string类型,XML解析器以String类型解析出数据,如果属性不是String类型,属性值会通过PropertyEditors转换为其他类型,比如时间类型.

2.注入bean

上面的代码中就注入了bean,在ServiceImpl中注入DaoImpl。可以使用ref来进行配置。

3.注入集合

常见的集合有list、map、set、property等,下面的代码是在ServiceImpl中定义了几个属性,然后在上下文中通过属性注入进去。为了测试,在DaoImpl中也增加了一个属性s。

package Cuiyw.Spring.Dao;
import java.util.Calendar;
import Cuiyw.Spring.IDao.IDao;
public class DaoImpl implements IDao{
 public String s;
 public String getS() {
  return s;
 }
 public void setS(String s) {
  this.s = s;
 }
 public String sayHello(String name) {
  int hour=Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
  if(hour<6) return "凌晨早,"+name;
  if(hour<12)return "早上好,"+name;
  if(hour<13)return "中午好,"+name;
  if(hour<18)return "下午好,"+name;
  return "晚上好,"+name+", s="+s;   
 } 
}
package Cuiyw.Spring.Service;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import Cuiyw.Spring.IDao.IDao;
import Cuiyw.Spring.IService.IService;
public class ServiceImpl implements IService{
 private IDao dao;
 private int baseProperty;
 private List<Object> lists;
 private Set<Object> sets;
 private Map<Object, Object> maps;
 private Properties pros;
 public IDao getDao() {
  return dao;
 }
 public void setDao(IDao dao) {
  this.dao = dao;
 }
 public void service(String name) {
  System.out.println(dao.sayHello(name)+",baseProperty:"+getBaseProperty());
  for(int i=0;i<lists.size();i++)
  {
   Object obj=lists.get(i);
   System.out.println(obj.getClass().getName());
  }
  for(Object obj : sets)
  {
   System.out.println(obj.getClass().getName());
  }
  //遍历maps中的key
  for (Object key : maps.keySet()) {
   System.out.println("Key = " + key);
  }
  //遍历maps中的值
  for (Object value : maps.values()) {
   System.out.println("Value = " + value);
  }
   Set<String> pro=pros.stringPropertyNames();
   Iterator<String> it=pro.iterator();
   while(it.hasNext()){
    Object key=it.next();
    System.out.println(key+"----"+pros.getProperty((String) key));
    }
 }
 public int getBaseProperty() {
  return baseProperty;
 }
 public void setBaseProperty(int baseProperty) {
  this.baseProperty = baseProperty;
 }
 public List<Object> getLists() {
  return lists;
 }
 public void setLists(List<Object> lists) {
  this.lists = lists;
 }
 public Set<Object> getSets() {
  return sets;
 }
 public void setSets(Set<Object> sets) {
  this.sets = sets;
 }
 public Map<Object, Object> getMaps() {
  return maps;
 }
 public void setMaps(Map<Object, Object> maps) {
  this.maps = maps;
 }
 public Properties getPros() {
  return pros;
 }
 public void setPros(Properties pros) {
  this.pros = pros;
 }
}

主要是注入的配置,在list、map、set属性中都是配置了一个基础类型value=1,两个DaoImpl类型。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="DaoImpl" class="Cuiyw.Spring.Dao.DaoImpl">
 <property name="s" value="cyw"></property>
</bean>
<bean id="ServiceImpl" class="Cuiyw.Spring.Service.ServiceImpl" scope="singleton" name="ServiceA">
 <property name="dao" ref="DaoImpl"></property>
 <property name="baseProperty" value="222"></property>
 <property name="lists">
   <list>
   <value>1</value>
   <ref bean="DaoImpl" />
   <bean class="Cuiyw.Spring.Dao.DaoImpl">
    <property name="s" value="cuiywlists" />
   </bean>
  </list>
 </property>
 <property name="sets">
   <set>
   <value>1</value>
   <ref bean="DaoImpl" />
   <bean class="Cuiyw.Spring.Dao.DaoImpl">
    <property name="s" value="cuiywsets" />
   </bean>
  </set>
 </property>
 <property name="maps">
   <map>
   <entry key="key1" value="1"></entry>
   <entry key="key2" value-ref="DaoImpl"></entry>
   <entry key="key3" >
   <bean class="Cuiyw.Spring.Dao.DaoImpl">
    <property name="s" value="cuiywmaps" />
   </bean>
   </entry>
  </map>
 </property>
 <property name="pros">
  <props>
   <prop key="prokey1">prokeyA</prop>
   <prop key="prokey2">prokeyB</prop>
  </props>
 </property>
</bean>
<alias name="ServiceA" alias="ServiceA1"/>
</beans>

执行main方法可以看到属性都注入进去了。

4.自定义属性编辑器

对于有一些属性是没法注入的,此时就需要自定义,比如上面说的日期类型。

首先是要定义一个继承PropertyEditorSupport的类,重写setAsText方法。

package Cuiyw.Spring.Service;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class CustomerProperty extends PropertyEditorSupport {
 private String format="yyyy-MM-dd";
 public String getFormat() {
  return format;
 }
 public void setFormat(String format) {
  this.format = format;
 }
 @Override
 public void setAsText(String text) throws IllegalArgumentException {
  // TODO Auto-generated method stub
  SimpleDateFormat sdf=new SimpleDateFormat(format);
  //super.setAsText(text);
  try {
   //转换对象,能过setValue方法重新赋值
   this.setValue(sdf.parse(text));
  } catch (ParseException e) {
   e.printStackTrace();
  }
 }
}

然后在配置文件配置这个类

<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
 <property name="customEditors">
 <map>
 <entry key="java.util.Date" value="Cuiyw.Spring.Service.CustomerProperty"/>
 </map>
 </property>
</bean>

这里还是在ServiceImpl中增加了一个java.util.Date类型的date属性。并在配置文件注入值。

<property name="date" value="2017-12-10"/>

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

相关文章

  • JavaWeb文件上传下载功能示例解析

    JavaWeb文件上传下载功能示例解析

    这篇文章主要介绍了JavaWeb中的文件上传和下载功能的实现,文件上传和下载功能是非常常用的功能,需要的朋友可以参考下
    2016-06-06
  • Java类加载器ClassLoader用法解析

    Java类加载器ClassLoader用法解析

    这篇文章主要介绍了Java类加载器ClassLoader用法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-02-02
  • Jenkins自动化部署SpringBoot项目的实现

    Jenkins自动化部署SpringBoot项目的实现

    本文主要介绍了Jenkins自动化部署SpringBoot项目的实现,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2023-01-01
  • javaSwing写关闭窗口的提示框实例

    javaSwing写关闭窗口的提示框实例

    这篇文章主要介绍了javaSwing写关闭窗口的提示框实例,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-12-12
  • jdk线程池的实现

    jdk线程池的实现

    本文主要介绍了jdk线程池的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • JDBC连接数据库步骤及基本操作示例详解

    JDBC连接数据库步骤及基本操作示例详解

    这篇文章主要为大家介绍了JDBC连接数据库步骤及基本操作示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-11-11
  • RabbitMq消息防丢失功能实现方式讲解

    RabbitMq消息防丢失功能实现方式讲解

    这篇文章主要介绍了RabbitMq消息防丢失功能实现,RabbitMQ中,消息丢失可以简单的分为两种:客户端丢失和服务端丢失。针对这两种消息丢失,RabbitMQ都给出了相应的解决方案
    2023-01-01
  • Spring Cloud Eureka 服务上下线监控的实现

    Spring Cloud Eureka 服务上下线监控的实现

    这篇文章主要介绍了Spring Cloud Eureka 服务上下线监控的实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-09-09
  • Java多线程案例之定时器详解

    Java多线程案例之定时器详解

    定时器是一种实际开发中非常常用的组件, 类似于一个 “闹钟”, 达到一个设定的时间之后, 就执行某个指定好的代码。本文主要来和大家聊聊定时器的原理与使用,需要的可以参考一下
    2023-01-01
  • 简单了解Spring中的事务控制

    简单了解Spring中的事务控制

    这篇文章主要介绍了简单了解Spring中的事务控制,事务是一组操作的执行单元,下面我们来简单学习一下吧
    2019-05-05

最新评论