Spring基本配置

1、配置准备:下载Spring和commons-logging的jar包
2、新建Java工程,将jar包导入工程中

或maven加载jar,spring的依赖共有以下四个方面:

1)spring核心依赖
spring-core、spring-beans、spring-context

2)spring dao依赖(提供JDBCTemplate)
spring-jdbc、spring-tx

3)spring web依赖
spring-web、spring-webmvc

4)spring test依赖
spring-test

然后编写spring的核心配置文件applicationContext.xml(名字任意,习惯名称),

习惯上: 在src建立applicationContext.xml(位置:src目录或者 WEB-INF目录)web项目,就放在resources目录即可。

将bean交给spring,那么就要在applicationContext.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"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    ">
    
    <bean id="hello" class="com.spring.test.HelloWorld">  
        <property name="info" value="Hello,This is my first Spring Application!"></property>  
    </bean> 
</beans>

 编写测试类TestMain.java

package com.spring.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestMain {
    
    public static void main(String[] args)
    {
        //读取配置文件
        ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
        //获取bean的实例
        HelloWorld t=(HelloWorld) ctx.getBean("hello");
        //调用方法
        System.out.println(t.getInfo());
    }
}

 

https://blog.csdn.net/sunzhitao1990/article/details/79196933
https://blog.csdn.net/sunzhitao1990/article/details/79189637

posted @ 2019-08-16 14:03  Nausicaa0505  阅读(145)  评论(0编辑  收藏  举报