spring 是一种容器框架在xml文件中装配bean的方式主要有下面三种
拿userService举个例子
一 直接通过 new实现类来实现
在beans.xml中配置的bean
<bean id="userService" class="com.lilang.service.UserServiceImpl"></bean>
写个接口,实现类大致如下图
具体代码如下
package com.lilang.service;
public interface IUserService {
public void add();
}
实现类 UserServiceImpl
package com.lilang.service;
public class UserServiceImpl implements IUserService {
private String name;
@Override
public void add() {
System.out.println("创建成功"+name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name =name;
}
}
在测试中首先通过 ApplicationContext进行连接初始化然后通过context.getBean通过id获得对象。
具体代码如下
package com.lilang.test;
import com.lilang.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
class DemoTestTest {
@org.junit.jupiter.api.Test
void test01() {
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml") ;
UserServiceImpl userService= (UserServiceImpl) context.getBean("userService");
userService.add();
}
}
运行出来结果
至于为什么会出现null是因为没有进行property注入。
第二种通过静态工厂的方法
<!-- 第二种方式:通过静态工厂方法
-->
<bean id="userService2" class="com.lilang.service.UserSereviceFactory1" factory-method="createUserService"></bean>
需要注意版本问题可能会出现版本不匹配的问题
类中多写一个工厂类类中有个创建userservice的方法其他的大致通第一个,如图
第三种方法:实例工厂方法
直接通过以下两个方法进行加载
factory-bean="factory2" factory-method="createUserService"