定义实体类
package world.xuewei; /** * 用户实体 * * @author 薛伟 * @since 2023/9/14 17:17 */ public class User { /** * 用户名 */ private String userName; /** * 密码 */ private String password; public User() { } public User(String userName, String password) { this.userName = userName; this.password = password; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "User{" + "userName='" + userName + '\'' + ", password='" + password + '\'' + '}'; } }
定义服务接口
package world.xuewei; /** * 用户服务接口 * * @author 薛伟 * @since 2023/9/14 17:17 */ public interface UserService { /** * 用户登录 * * @param userName 用户名 * @param password 密码 * @return 登录用户 */ User login(String userName, String password); }
定义服务实现类
package world.xuewei; /** * 用户服务接口实现类 * * @author 薛伟 * @since 2023/9/14 17:19 */ public class UserServiceImpl implements UserService { @Override public User login(String userName, String password) { System.out.println("当前登录用户为:" + userName); return new User(userName, password); } }
定义工厂类
package world.xuewei; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * 工厂类 * * @author 薛伟 * @since 2023/9/14 17:23 */ public class BeanFactory { /** * 存储配置文件内容 */ private static final Properties properties = new Properties(); static { // 加载配置文件内容 try (InputStream inputStream = BeanFactory.class.getResourceAsStream("/bean.properties")) { properties.load(inputStream); } catch (IOException e) { throw new RuntimeException(e); } } /** * 获取 Bean 对象 * * @return 服务实现类 */ public static Object getBean(String beanName) { Object bean = null; try { // 通过全限定类名反射创建对象 Class<?> userServiceClass = Class.forName(String.valueOf(properties.get(beanName))); bean = userServiceClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } return bean; } }
测试方法
package world.xuewei; /** * 主方法 * * @author 薛伟 * @since 2023/9/14 17:21 */ public class MainApp { public static void main(String[] args) { UserService userService = (UserService) BeanFactory.getBean("userService"); userService.login("张三", "123456"); } }
配置文件
# bean.properties userService=world.xuewei.UserServiceImpl