Spring 4 Quick Start and spring Quick Start
The demo in this article is based on the entry case on the spring official website. Of course, I made some changes.
Spring official site case: http://projects.spring.io/spring-framework/
The structure of my maven web project is as follows:
Add spring dependency to pom. xml:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.9.RELEASE</version> </dependency>
Next, we will start to create the required classes:
package com.mm.service;public interface MessageService {String getMessage();}
package com.mm.service.impl;import com.mm.service.MessageService;public class MessageServiceImpl implements MessageService{@Overridepublic String getMessage() {return "hello mm";}}
Here I don't need to inject in the form of spring configuration files, so I created a configuration file class
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(); }}
Create a bean to call the service
package com.mm.main.spring;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import com.mm.service.MessageService;@Componentpublic class MessagePrinter {@Autowiredprivate MessageService messageService;public void printMessage() { System.out.println(this.messageService.getMessage()); }}
Finally, write the client
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();}}
Background printing is as follows:
Next, we use annotation injection. First, we remove the MessageService bean in the configuration file class.
@Configuration@ComponentScan(basePackages = "com.mm")public class ApplicationConfig {// @Bean// MessageService messageService() {// return new MessageServiceImpl();// }}
Add annotation for MessageServiceImpl
@ Service // public class MessageServiceImpl implements MessageService {@ Override public String getMessage () {return "hello mm ";}}
Same output