ApplicationContext用法示例


1、通過ApplicationContext將bean注入容器中

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class ApplicationContextTest {

    @Bean(name="user")
    @Scope("singleton")
    public User ttt() {
        User user = new User();
        user.setName("user_1");
        user.setPwd("1234");
        return user;
    }
    
    public static void main(String[] args) {
        
        //通過applicationContext方式
        ApplicationContext atc = new AnnotationConfigApplicationContext(ApplicationContextTest.class);
        User user = (User)atc.getBean("user");
        System.out.println(user.getPwd());
        
        //通過注冊的方式
        AnnotationConfigApplicationContext acc = new AnnotationConfigApplicationContext();
        acc.register(ApplicationContextTest.class);
        acc.refresh();
        User _user = (User)acc.getBean("user");
        System.out.println(_user.getName());
    }
}

class User {
    
    private String name;
    private String pwd;
    
    public User() {
        
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public User(String name, String pwd) {
        this.name = name;
        this.pwd = pwd;
    }
    
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM