Spring learning factory class and configuration file

bean.properties

userMapper=top.chenyp.mapper.impl.UserMapperImpl
userService=top.chenyp.service.impl.UserServiceImpl

mapper

public interface UserMapper {
    
    

    void findById(String id);

}

public class UserMapperImpl implements UserMapper {
    
    
    @Override
    public void findById(String id) {
    
    

        System.out.println("hello");

    }
}


service

public interface UserService {
    
    
    void findById(String id);
}

public class UserServiceImpl implements UserService {
    
    

    private UserMapper mapper = (UserMapper) BeanFactory.getBean("userMapper");


    @Override
    public void findById(String id) {
    
    
        mapper.findById(id);
    }
}

Factory class

public class BeanFactory {
    
    
    private static Properties props;
    //定义一个map对象,存储容器
    private static Map<String,Object> beans;
    static {
    
    
        System.out.println("哈哈哈");
        try {
    
    
            props=new Properties();
            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            props.load(in);

            beans=new HashMap<>();

            //取出配置文件中所有的key
            Enumeration<Object> keys = props.keys();

            while (keys.hasMoreElements()) {
    
    
                //取出每个key
                String key = keys.nextElement().toString();
                //根据key获取value;

                String beanPath = props.getProperty(key);

                //反射创建对象
                Object value = Class.forName(beanPath).newInstance();

                beans.put(key,value);

            }
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }

    }


    public static Object getBean(String beanName){
    
    

        return beans.get(beanName);

    }

}

transfer

public static void main(String[] args) {
    
    

        UserService userMapper = (UserService) BeanFactory.getBean("userService");

        userMapper.findById("123456");

    }

Guess you like

Origin blog.csdn.net/qq_42794826/article/details/114375300