栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring基于java注解方式注册javabean关键代码:AnnotationConfigApplicationContext

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring基于java注解方式注册javabean关键代码:AnnotationConfigApplicationContext

pom文件


    4.0.0

    com.burns.spring.framework.test
    spring-framework-test-20220516
    1.0-SNAPSHOT

    
        8
        8
    

    
        
            
                org.springframework.boot
                spring-boot-starter-parent
                2.5.13
                import
                pom
            
        
    

    
        
            org.springframework
            spring-context
        
    

程序入口:Application
package com.burns.spring.framework.test;

import com.burns.spring.framework.test.component.MessagePrinter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Scope;

@ComponentScan
public class Application {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
        MessagePrinter printer = context.getBean(MessagePrinter.class);
        printer.pringMessage();
    }
}
MessagePrinter
package com.burns.spring.framework.test.component;

import com.burns.spring.framework.test.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MessagePrinter {
    final private MessageService messageService;

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

    public void pringMessage() {
        System.out.println(this.messageService.getMessage());
    }


}
服务接口:MessageService
package com.burns.spring.framework.test.service;

public interface MessageService {
    String getMessage();

}
服务实现类:MessageServiceImpl
package com.burns.spring.framework.test.service.impl;

import com.burns.spring.framework.test.service.MessageService;
import org.springframework.stereotype.Service;

@Service
public class MessageServiceImpl implements MessageService {
    @Override
    public String getMessage() {
        return "Hello World!";
    }
}
spring注册bean关键位置

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/915022.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号