从0到1学JAVA第十一天——Spring入门学习之编写第一个Spring实例

By | 12月 5, 2017

1.Spring是什么?

Spring是一个非常强大的反转控制(IOC)框架,以帮助分离项目组件之间的依赖关系,贯穿于表现层、业务层、持久层。

2.MyEclipse 2017 JAVA项目配置Spring

2.1右键项目名称依次找到Configure Facets……,Manage。

2.2左侧栏中选中Project Facets,然后在右侧会出现很多模板,然后选中采用Spring,最右侧可以选择Spring的版本,最新版本是Spring 4.1。

2.3左侧栏中选中Project Libraries,右侧可以看到已经引入的Spring的库文件,可以自行选择相应的jar包。

3.动手编写第一个Spring实例

3.1Spring实例目录

3.2 Spring bean 配置文件——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-4.1.xsd">
    <bean id="helloID" class="pers.onezero.spring.Hello10">
        <property name="name" value="onezero"/>
    </bean>
</beans>

3.3 功能函数——Hello10.java

package pers.onezero.spring;

public class Hello10 {
	private String name;
	
	public void setName(String name){
		this.name = name;
	}
	
	public void printName(){
		System.out.println("Spring:Hello:"+name);
	}
}

3.3  main函数——APP.java

注意引入ApplicationContext和ClassPathXmlApplicationContext两个包。

package pers.onezero.spring;

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

public class App 
{
	
	
    public static void main( String[] args )
    {
    	ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");                                    #此处引入的是Spring bean配置文件
    	Hello10 obj = (Hello10) context.getBean("helloID");   #helloID是在配置文件中设置的ID   
    	obj.printName(); 
    }
    
}

3.4运行结果如下

4.遇到的问题

4.1log4j警告

log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

如图:

出现这个警告信息的原因是log4j无法输出日志,需要增加log4j.properties文件,文件内容如下:

# Configure logging for testing: optionally with log file
log4j.rootLogger=WARN, stdout
# log4j.rootLogger=WARN, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

之后将文件放置在src目录下或者/WEB-INF/classes目录下。此处一零将文件放置src/main/java目录下,完成后才能提示完整的错误信息

本文相关代码已上传github,源码目录LearnSpring

发表评论

您的电子邮箱地址不会被公开。