【spring】写一个HelloSpring

编程入门 行业动态 更新时间:2024-10-15 08:24:39

【<a href=https://www.elefans.com/category/jswz/34/1769862.html style=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

本文发布于:2023-11-16 12:17:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622093.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:spring   HelloSpring

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!