1.普通Bean:在配置文件中定义bean类型就是返回类型
定义一个class
package com.hhm.spring5;
public class User {
public void add(){
System.out.println("add.......");
}
}
定义xml
<bean id="user" class="com.hhm.spring5.User"></bean>
测试方法:
@Test
public void testAdd() {
//1.加载spring配置文件
ApplicationContext context =
new ClassPathXmlApplicationContext("bean1.xml");
User user = context.getBean("user", User.class);
System.out.println(user);
user.add();
}
2. 工厂Bean:在配置文件定义bean类型可以和返回类型不一样
新建 MyBean类
package com.hhm.spring5;
import org.springframework.beans.factory.FactoryBean;
public class MyBean implements FactoryBean {
@Override
public Object getObject() throws Exception {
return null;
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public boolean isSingleton() {
return false;
}
}
定义xml
<bean id="mybean" class="com.hhm.spring5.MyBean"></bean>
测试方法:
@Test
public void testMyBean() {
//1.加载spring配置文件
ApplicationContext context =
new ClassPathXmlApplicationContext("bean1.xml");
MyBean mybean = context.getBean("mybean", MyBean.class);
System.out.println(mybean);
}
发现会报错:
错误为:
org.springframework.beans.factory.BeanNotOfRequiredTypeException:
Bean named 'mybean' is expected to be of type
'com.hhm.spring5.MyBean' but was actually of type
'org.springframework.beans.factory.support.NullBean'
意思是期望是 com.hhm.spring5.MyBean 可实际上是 org.springframework.beans.factory.support.NullBean
如果MyBean类的代码改成:
@Override
public Object getObject() throws Exception {
return "hello";
}
又会报错为:
org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'mybean' is expected to be of type 'com.hhm.spring5.MyBean' but was actually of type 'java.lang.String'
期望的是 com.hhm.spring5.MyBean 结果实际上是 java.lang.String
也就是说这边会动态返回你指定的类型。
再次改造一下:注意接口中加入了字符串的类型
public class MyBean implements FactoryBean<String> {
@Override
public String getObject() throws Exception {
return "hello world!";
}
测试类也需要定义返回的类型:
@Test
public void testMyBean() {
//1.加载spring配置文件
ApplicationContext context =
new ClassPathXmlApplicationContext("bean1.xml");
String mybean = context.getBean("mybean", String.class);
System.out.println(mybean);
}
结果输出:
hello world!
============================================================================
其实按默认就好, return返回什么类型,测试的时候强转即可。
public class MyBean implements FactoryBean {
@Override
public Object getObject() throws Exception {
return "hello world!";
}
@Test
public void testMyBean() {
//1.加载spring配置文件
ApplicationContext context =
new ClassPathXmlApplicationContext("bean1.xml");
Object mybean = context.getBean("mybean", Object.class);
System.out.println(mybean);
}
输出:
hello world!
或者:
@Override
public Object getObject() throws Exception {
return new User(); //实际中不会这么创建
}
@Test
public void testMyBean() {
//1.加载spring配置文件
ApplicationContext context =
new ClassPathXmlApplicationContext("bean1.xml");
Object mybean = context.getBean("mybean", Object.class);
User user = (User)mybean;
user.add();
}
输出:
add.......