Spring学习笔记-1

简单记录一下学习内容

首先贴上官网链接 https://spring.io/

使用的平台是 intellij idea


先是概念性的东西,简单概述一下 spring 框架的内容

Spring 是一个非常活跃的开源框架,帮助公司分离项目组件之间的关系。

Spring 有以下几大特点:

IOC -- inversion of control  控制反转

简单的来说就是创建对象和对象之间的依赖维护 控制权由程序员变成了  Spring(托管)。

DI -- dependec of injection 依赖注入
就是 spring 对象之间依赖关系的创建。 可以通过 annotation 和 xml 两种方式实现。

AOP -- aspect oriented programming
面向切面编程(目前不是很懂)

几大核心块
Core containner
core: IOC DI
beans: 创建对象的工厂
Context: IOC容器, 其实就是 Spring 容器
SpEL:Spring 表达语言

Data access:
JDBC: 你懂得
ORM:对象关系映射
OXM: 对象和xml转换
JMS:生产消费
Transcations:事务管理

Web:
面向web 应用程序

portlet 首页的窗口

Spring 包含 Spring MVC 

快速创建流程

在 ideallij 中用 maven 方式创建新工程,在 pom 中添加依赖, 在 artifacrt-id 中输入 spring-context 会自动生成相关文件,点击 import 即可。

当然,你直接创建 Spring 工程文件也行。

不同的 Spring 容器使用方法

注释方式

@Component  写在类前面,使得当前类在未来创建对象时不需要 new 关键字。

@ComponentScan 一般用于主程序,会扫描所有的 @Component 。

ApplicationContext context = new AnnotationConfigApplicationContext();

这一句话会创建所有有相关注释的类的实例,并把其放在 Spring 容器中。
AnnotationConfigApplicationContext() 括号中的内容是 Spring 容器(主程序)所在位置(@ComponentScan 所在位置)比如 application.class。

MessagePrinter printer = context.getBean(MessagePrinter.class);

通过特定类可以从容器中获取到实例。


@Autowired 

写在方法前,被其注释的方法会在实例创建时自动调用。比如我需要传一个 service 对象给 printer 才能完成 setter 的操作,但如果加上这个会自动 创建并且调用 setter。

这个之后会再单独陈述。


XML 方式

<!--
        bean元素表示当前元素需要 spring 容器管理
        id 属性 标识对象 未来在应用程序中通过id 获取对象
        class 被管理对象的类的全名
    -->
    <bean id="service" class="hello.MessageService"></bean>
    <bean id="printer" class="hello.MessagePrinter">
	(// 依赖,name 指类下面的对象名 ref 指 id 这句话不要复制进去)
        <property name="service" ref="service"></property>
    </bean>

虽然不用任何注释了,上面的获取容器方法的语句要重新写过。

ApplicationContext context = new ClassPathXmlApplicationContext("application_context.xml");


引入log4j2

添加依赖

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.11.0</version>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.11.0</version>
  </dependency>

在 res 下创建 log4j2.properties

输入以下文字

status = warn
name = MyApp

filter.threshold.type = ThresholdFilter
filter.threshold.level = debug

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %m%n

appender.rolling.type = File
appender.rolling.name = log
appender.rolling.append = true
appender.rolling.fileName = e:\\test1.log
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d-%m%n

rootLogger.level = debug
rootLogger.appenderRef.stdout.ref = STDOUT
rootLogger.appenderRef.log.ref = log

再次运行就能看到全部过程了!


P.S. 

ideallij 里面的几个快捷键

sout 打印

ctrl + o 快速创建构造方法(第一个 object())

alt + insert 可以自动生成 setter 方法

ctrl+ space 快速填充

alt + enter 删除无用引用



猜你喜欢

转载自blog.csdn.net/weixin_42271658/article/details/80412443