Spring第一个程序

使用工具:idea2018.3 ,maven3.6

step.1

maven倚赖:

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

step.2

创建服务类:

  1. 创建接口 MessageService
public interface MessageService {
	String getMessage();
}
  1. 实现接口类:MessageServiceImpl
@Service
public class MessageServiceImpl implements MessageService {
	
	public String getMessage() {
		return "Hello World!";
	}

}
  • 其中Service(和后面的Component)注解该类是一个spring bean

step.3

创建打印器MessagePrinter :

@Component
public class MessagePrinter {

    final private MessageService service;

    @Autowired
    public MessagePrinter(MessageService service) {
        this.service = service;//通过Autowired,将MessageService自动注入
    }

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

step.4

创建应用主类:

@ComponentScan
public class Application {

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

}
  • 其中MessagePrinter ,不需要通过new来实例化,而是直接从spring容器中取出
  • AnnotationConfigApplicationContext是上下文的一种实现方式
  • @ComponentScan会扫描指定包下的所有标有@Component的类,并装配为bean
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值