学习Spring有关知识

初学者,一般掌握Spring四个方面的功能:

1.IOC/DI

2.AOP

3.事务

4.Jdbc Template

 

IOC初体验

首先创建一个普通的Maven项目,在pom.xml文件中,引入spring-context依赖,如下

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
</dependencies>

接下来,在resources目录下创建一个spring的配置文件(注意要先添加依赖,后创建配置文件)
1.右击鼠标(在resources上)->选择NEW->选择XML Configuration File->点击Spring Config(注意,如果没有引入依赖,不会出现Spring Config),
创建一个配置文件(作者自定义配置文件名:applicationContext.xml)命名自定义。
2.在这个文件中,我们可以配置所有需要注册到Spring容器的Bean:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="org.yadianna.test.Cook" id="cook"/> //注册到Spring容器的Bean
</beans>
class属性表示需要注册的bean的全路径,id则表示bean的唯一标识,一般情况下可以用name属性作为bean标记,但最好不用。
接下来,(在项目的主方法main中)加载这个配置文件:
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); //导入刚才自定义的配置文件名即可
3.通过getBean方法,可以从容器中去获得对象:
Cook cook=(Cook)ctx.getBean("cook");


 

posted @ 2020-07-22 21:01  雅典娜Athena  阅读(125)  评论(0编辑  收藏  举报