AnnotationConfigApplictionContext源码分析

来源:互联网 发布:自动麻将机作弊软件 编辑:程序博客网 时间:2024/06/05 12:45

以下是对AnnotationConfigApplicationContext类进行源码分析

创建接口:
MessageService.java

package com.my.web.service;/** * Created by yexianxun on 2017/2/20. */public interface MessageService {    String getMessage();}

UserService.java

package com.my.web.service;/** * Created by yexianxun on 2017/2/21. */public interface UserService {    void addUser();}

MessagePrinter.java

package com.my.web;import com.my.web.service.MessageService;import com.my.web.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;/** * Created by yexianxun on 2017/2/20. */@Componentpublic class MessagePrinter {    final MessageService messageService;    @Autowired    public MessagePrinter(MessageService messageService) {        this.messageService = messageService;    }    @Autowired    private UserService userService;    public void printMessage() {        System.out.println(messageService.getMessage());        userService.addUser();    }}

UserServiceImpl.java

package com.my.web.service.impl;import com.my.web.service.UserService;import org.springframework.stereotype.Component;/** * Created by yexianxun on 2017/2/21. */@Componentpublic class UserServiceImpl implements UserService {    @Override    public void addUser() {        System.out.println("add a user");    }}

Application.java

package com.my.web;import com.my.web.service.MessageService;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.*;/** * Created by yexianxun on 2017/2/20. */@Configuration@ComponentScanpublic class Application {    @Bean    MessageService mockMessageService() {        return new MessageService() {            @Override            public String getMessage() {                return "hello world";            }        };    }    public static void main(String[] args) {        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Application.class);        MessagePrinter printer = applicationContext.getBean(MessagePrinter.class);        printer.printMessage();    }}

@Controller、@Service、@Component、@Repository主要替换bean在xml中定义,而是通过以上注解定义。这四个主要区别:
@Controller 主要标识控制层类
@Service 主要标识业务层类
@Repository 主要标识数据访问层类
@Component 主要标识组件类
四个注解对应的BeanDefinition会有差异,但是功能是一样的。

@ComponentScan 注解与配置文件中 <context:component-scan base-package="com.adtime.bullbat.client"/>相似。

0 0
原创粉丝点击