wangzhibo-spring

我的第一个Spring程序

package com.zhida.spring6.bean

/**
* 作者: 王志博
*
* @version 1.0
* @create 2022/11/17 16:25
* @since 1.0
* 创建类
*/
public class User {
//Spring会通过反射机制,调用类的无参构造方法来实例化对象

public User() {
System.out.println("User无参构造方法执行!");
}
}


在resources目录下创建Spring6.xml文件

<?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">

<!--名字随意,不一定叫spring.xml-->
<!--最好放根目录下-->
<!--配置bean-->
<!--
bean标签的两个重要属性:
id:是这个bean的身份证号,不能重复,唯一标识
class:必须填写类的全限定类名.
-->
<bean id="userBean" class="com.zhida.spring6.bean.User"/>

<bean id="nowTime" class="java.util.Date"/>
</beans>

创建Spring测试类
@Test
public void testBeanFactory(){
//ApplicationContext接口的超级父接口:BeanFactory
//BeanFactory是IOC容器的顶级接口,底层是工厂模式
//XML解析 + 工厂模式 + 反射机制
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring6.xml");
User userBean = applicationContext.getBean("userBean", User.class);
System.out.println(userBean);
}

执行测试后:输出构造方法和userBean的Hash值
注意:构造方法是创建容器时执行

posted on 2022-11-18 14:10  王志博  阅读(14)  评论(0编辑  收藏  举报

导航