首页 > 移动平台 > 详细

使用AnnotationConfigApplicationContext装备Bean到IoC容器

时间:2020-04-11 10:53:52      阅读:56      评论:0      收藏:0      [点我收藏+]
package com.springboot.chapter3.pojo;

public class User {
    private Long id;

    private String userName;

    private String note;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }
}
package com.springboot.chapter3.config;

import com.springboot.chapter3.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/*@Configuration代表这是一个Java配置文件,Spring的容器会根据它来生成IoC容器去装配Bean*/
@Configuration
public class AppConfig {
    /*@Bean代表将initUser方法返回的POJP装配到IoC容器中,其属性name定义了这个Bean的名称,
    如果没有配置它,则将方法名称“initUser”作为Bean的名称保存到Spring IoC容器中*/
    @Bean(name = "user")
    public User initUser() {
        User user = new User();
        user.setId(1L);
        user.setUserName("user_name_1");
        user.setNote("note_1");
        return user;
    }
}
package com.springboot.chapter3.config;

import com.springboot.chapter3.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.util.logging.Logger;

public class IoCTest {
    private static Logger log = Logger.getLogger(String.valueOf(IoCTest.class));

    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
        User user = ctx.getBean(User.class);
        log.info(user.getUserName());
    }
}

使用AnnotationConfigApplicationContext装备Bean到IoC容器

原文:https://www.cnblogs.com/xl4ng/p/12677767.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!