常用的从容器中获取bean实例使用这样的方式:
@Test public void test() { Persion p = (Persion) ioc.getBean("p1"); System.out.println(p); }常用的在容器中配置组件使用这样的方式:
<bean id="p1" class="com.gql.bean.Persion"> <property name="name" value="张三"></property> <property name="age" value="18"></property> <property name="email" value="zs@163.com"></property> <property name="gender" value="男"></property> </bean>下面的实验介绍一些Spring容器中注册组件对象的其他方法。
实验1:根据bean的类型从ioc容器中获取实例
@Test public void test01() { Persion p = ioc.getBean(Persion.class); System.out.println(p); }这种方法查找的好处是不需要类型转换,但是如果ioc容器中要找的bean有多个,使用这种方法查找就会报错。可以改用下面的方式:
@Test public void test01() { Persion p = ioc.getBean("p1", Persion.class); System.out.println(p); }实验2:通过有参构造器为bean的属性赋值
需要提前在bean中添加有参构造器,才能进行下面的测试。
<bean id="p2" class="com.gql.bean.Persion"> <constructor-arg name="name" value="李四"></constructor-arg> <constructor-arg name="age" value="22"></constructor-arg> <constructor-arg name="email" value="ls@163.com"></constructor-arg> <constructor-arg name="gender" value="男"></constructor-arg> </bean>使用这种有参构造器为bean的属性赋值,可以省略name,但是value的顺序必须与bean中的顺序一致。(若再使用index和type进行索引,可以不按顺序)
通过名称空间为bean赋值:
添加p命名空间标签头:xmlns:p=“http://boPooledDataSource"> <property name="user" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> </bean>
测试:
@Test public void test12() throws SQLException { DataSource bean2 = ioc.getBean(DataSource.class); System.out.println(bean2.getConnection()); }到此这篇关于Spring框架花式创建Bean的n种方法的文章就介绍到这了,更多相关Spring 创建Bean内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!