spring】写一个HelloSpring"/>
【spring】写一个HelloSpring
方法实现
1.创建一个接口
package org.example.dao;public interface HelloDao {void sayHello();
}
接口名为HelloDao
定义了一个sayHello方法
2.创建一个实现类
package org.example.dao;public class HelloDaoImpl implements HelloDao{@Overridepublic void sayHello() {System.out.println("Hello Spring");}
}
调用(HelloDao )接口
重写该方法 (输出"Hello Spring" )
3.在resource包下创建beans.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""xmlns:xsi=""xsi:schemaLocation="://www.springframework/schema/beans/spring-beans.xsd"><!--使用spring来创建对象,在Spring这些称为bean --><bean id="hello" class="org.example.dao.HelloDaoImpl"></bean></beans>
4.测试
package org.example;import javafx.application.Application;
import org.example.dao.HelloDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Test {public static void main(String[] args) {//初始化spring容器 ApplicationContext,加载配置文件ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");//通过容器获取test实例 test为配置文件中的idHelloDaoImpl hello= (HelloDaoImpl) context.getBean("hello");hello.sayHello();}
}
总结
HelloDao对象是谁创建的?
spring创建的
怎么创建的?
<bean id="hello" class="org.example.dao.HelloDaoImpl"></bean>
been=对象
Java中创建对象
类型 变量=new 类型 ();
id="hello " hello=变量名
class=" " new 的对象
在bean配置对象,相当于交给了bean管理,用的时候直接在容器里拿出来
更多推荐
【spring】写一个HelloSpring
发布评论