1. 程式人生 > >Spring4快速入門

Spring4快速入門

context art ide ack 後臺 改變 hello cts package

本篇文章的demo基於spring官網入門案例。當然,我做了一些改變。

spring官網案例:http://projects.spring.io/spring-framework/

我的maven web項目結構如下:

技術分享

在pom.xml中添加spring的依賴:

<dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>

接下來我們開始創建需要用到的類:
package com.mm.service;

public interface MessageService {
	String getMessage();
}

 

package com.mm.service.impl;

import com.mm.service.MessageService;

public class MessageServiceImpl implements MessageService{
	@Override
	public String getMessage() {
		return "hello mm";
	}
}

這裏我不用spring配置文件形式的註入,於是,我新建了一個配置文件類

package com.mm.main.spring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.mm.service.MessageService;
import com.mm.service.impl.MessageServiceImpl;

@Configuration
@ComponentScan(basePackages = "com.mm")
public class ApplicationConfig {
    @Bean
    MessageService messageService() {
        return new MessageServiceImpl();
    }
}

新建一個bean來調用服務

package com.mm.main.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.mm.service.MessageService;

@Component
public class MessagePrinter {
	@Autowired
	private MessageService messageService;
	public void printMessage() {
        System.out.println(this.messageService.getMessage());
    }
}

最後完成客戶端的編寫工作

package com.mm.main.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Client {
	public static void main(String[] args) {
		ApplicationContext context=new AnnotationConfigApplicationContext(ApplicationConfig.class);
		MessagePrinter messagePrinter=context.getBean(MessagePrinter.class);
		messagePrinter.printMessage();
	}
}

後臺打印如下:

技術分享

接下來我們用註解的方式註入,首先去掉配置文件類中的MessageService bean

@Configuration
@ComponentScan(basePackages = "com.mm")
public class ApplicationConfig {
//    @Bean
//    MessageService messageService() {
//        return new MessageServiceImpl();
//    }
}

為MessageServiceImpl添加註解

@Service//註解方式
public class MessageServiceImpl implements MessageService{
    @Override
    public String getMessage() {
        return "hello mm";
    }
}

同樣完成輸出

技術分享

  

  

  

 

Spring4快速入門