Spring入门一

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hlw521hxq/article/details/87655507

Spring入门学习

首先认识下Spring的结构

架构图

然后我们皆可以写我们的demo了

我们的Bean类

对于bean的理解,希望大家是把他看成Object对象,他可以是任何对象,甚至是接口,甚至是抽象方法,当然,具体用法大家在以后的使用中会有所认识的;

写一个简单的bean类

package mybatis.study.start.bean;

import lombok.Setter;

/**
 * @program: test
 * @description: helloworld
 * @author: cutedog
 * @create: 2019-02-18 22:48
 **/
@Setter
public class HelloWorld {
    private String name;
    public void pritlnHello(){
        System.out.println("Spring 3:Hello");
    }
}



写我们的配置文件

一般都是application.xml文件,放在idea的resource目录下,是一个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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

<bean id="helloBean" class="mybatis.study.start.bean.HelloWorld">
    <property name="name" value="Yiibai" />
</bean>

</beans>

** 重点看以上配置文件 **
除了http://www.springframework.org/schema/beans,注册命名空间以外,其他的都是根据开发需求进行添加
aop: 切面 应用场景: 日志,功能扩展
context: 上下文 应用场景: 用于spring-web中,作为上下文的连接
tx: 事务 ,数据回滚,具体可以之后跟大家说 应用场景: 持久层框架整合
还有spring的权限控制,有兴趣的大家可以了解下

最后就是我们的测试类

package mybatis.study.start.mapper.bean;

import mybatis.study.start.bean.HelloWorld;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @program: test
 * @description: spring配置内容
 * @author: cutedog
 * @create: 2019-02-18 23:02
 **/
public class HelloWorldTest {
    @Test
    public void hellotest(){
    //加载配置文件
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("mybatisDemo/application.xml");
        //通过配置文件获取注册beanid获取bean
        HelloWorld helloWorld = (HelloWorld)context.getBean("helloBean");
        //操作bean的方法
        helloWorld.pritlnHello();
    }
}

以上内容部分参考其他博客

例如:https://blog.csdn.net/u014510892/article/details/80836512

猜你喜欢

转载自blog.csdn.net/hlw521hxq/article/details/87655507