spring 核心组件 bean demo

其他技术

2017-12-11

186

0

技术:java8 +spring 5.0.2.RELEASE

运行环境:IDEA 15.2 + jdk8 + windows 10

demo功能:提供一个spring 核心组件 bean demo

源代码

https://gitee.com/youlixishi/demo-world/tree/master/src/spring/spring-context

Startup.java

package com.demoworld;

import com.demoworld.hello.MessagePrinter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * Created by francis on 2017/12/11.
 */
@Configuration
@ComponentScan
public class Startup {

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

MessagePrinter.java

package com.demoworld.hello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by francis on 2017/12/11.
 */
@Service
public class MessagePrinter {
    final private MessageService service;

    @Autowired
    public MessagePrinter(MessageService service) {
        this.service = service;
    }

    public void printMessage() {
        System.out.println(this.service.getMessage());
    }
}

IMessageService.java

package com.demoworld.hello;

/**
 * Created by francis on 2017/12/11.
 */
public interface IMessageService {
    String getMessage();
}

 

MessageService.java

package com.demoworld.hello;

import org.springframework.stereotype.Component;

/**
 * Created by francis on 2017/12/11.
 */
@Component
public class MessageService implements IMessageService {
    public String getMessage() {
        return "这个是啥";
    }
}
 

欢迎添加微信,互相学习↑↑↑ -_-

发表评论

全部评论:0条

白老虎

programming is not only to solve problems, ways to think