MyEclipse 10.7 + Spring 4.2手动配置
利用MyEclipe自带的Spring
1,创建项目
打开MyEclipse, 选择 File -> New -> Java Project
2, 添加Spring 3.1
选中新建的项目,右健 My Eclipse -> Add Spring Capabilities, 勾选 Spring 3.1 Core Libaries
以上方式可以简单的为项目添加Spring框架,但限制条件是Spring 版本只能为3.1
手动添加Spring 4.2
1, 下载必要的jar包
通过http://repo.spring.io/milestone/org/springframework/地址,逐个下载以下文件
commons-logging.jar spring-aop-4.2.0.RC3.jar spring-beans-4.2.0.RC3.jar spring-context-4.2.0.RC3.jar spring-context-support-4.2.0.RC3.jar spring-core-4.2.0.RC3.jar spring-expression-4.2.0.RC3.jar
2,把上面的包加到编译路径中
3,参照http://projects.spring.io/spring-framework/入门示例,Copy代码
MessageService.java
package com.bf; public interface MessageService { String getMessage(); }
MessagePrinter.java
package com.bf; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class MessagePrinter { final private MessageService service; @Autowired public MessagePrinter(MessageService service) { this.service = service; } public void printMessage() { System.out.println(this.service.getMessage()); } }
Application.java
package com.bf; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.*; @Configuration @ComponentScan public class Application { @Bean MessageService mockMessageService() { return new MessageService() { public String getMessage() { return "Hello World!"; } }; } public static void main(String[] args) { ApplicationContext context = new AnnotationConfigApplicationContext(Application.class); MessagePrinter printer = context.getBean(MessagePrinter.class); printer.printMessage(); } }
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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config /> <!--可以不要这一行--> <context:component-scan base-package="com.bf"/><!--可以不要这一行--> </beans>
编译通过过,直接点击Run Application, 输出“Hello World”
签名:删除冗余的代码最开心,找不到删除的代码最痛苦!