配置文件添加factory-method参数
<?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="userDao" class="com.example.demo.factory.StaticFactory" factory-method="getUserDao"></bean>
</beans>
工厂方法编写
package com.example.demo.factory;
import com.example.demo.dao.Impl.UserDaoImpl;
import com.example.demo.dao.UserDao;
public class StaticFactory {
public static UserDao getUserDao(){
return new UserDaoImpl();
}
}
Dao包编写
Dao接口
package com.example.demo.dao;
public interface UserDao {
public void save();
}
Dao接口实现类编写
package com.example.demo.dao.Impl;
import com.example.demo.dao.UserDao;
public class UserDaoImpl implements UserDao {
public UserDaoImpl() {
System.out.println("UserDaoImpl被创建了");
}
@Override
public void save() {
System.out.println("hello");
}
}
运行代码编写
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) app.getBean("userDao");
userDao.save();