spring容器创建对象原理

2020-07-23  本文已影响0人  simplerandom

多例对象

public class Test {
    public static void main(String[] args)
            throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        // 加载类路径下配置文件
        InputStream resourceAsStream = Test.class.getClassLoader().getResourceAsStream("class.properties");
        Properties properties = new Properties();
        properties.load(resourceAsStream);
        Object hello = properties.get("hello");
        System.out.println(hello);
        // 根据全限定类目创建对象
        Class<Hello> aClass = (Class<Hello>) Class.forName((String) hello);
        System.out.println(aClass.newInstance().toString());
    }
}

单例对象

public class Test {
static  HashMap<String, Object> map = new HashMap<>();
    public static void main(String[] args)
            throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        // 加载类路径下配置文件
        InputStream resourceAsStream = Test.class.getClassLoader().getResourceAsStream("class.properties");
        Properties properties = new Properties();
        properties.load(resourceAsStream);
        Object hello = properties.get("hello");
        System.out.println(hello);
        // 根据全限定类目创建对象
        Class<Hello> aClass = (Class<Hello>) Class.forName((String) hello);
        Hello instance = aClass.newInstance();
        map.put("hello",instance);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读