JAVA 核心笔记 || [xxx] Spring 之 JavaConfig 注解

JavaConfig 注解

作用:将Bean 配置 在 JAVA 类中

用法

App.java

import com.mj.bean.*;
import com.mj.bean.annotation.BeanConfig;
import com.mj.bean.annotation.BeanPerson;
import com.mj.bean.annotation.IBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import java.io.FileNotFoundException;

public class App {



    public static void main(String args[]) throws FileNotFoundException{
        /*
        //ClassPathXmlApplicationContext
        ApplicationContext context = new ClassPathXmlApplicationContext("com/mj/xml/Bean.xml");
        BeanSay sa = (BeanSay) context.getBean("BeanSay");
        sa.setMsg("__Spring");
        sa.talk();

        //FileSystemXmlApplicationContext
        ApplicationContext fileContext = new FileSystemXmlApplicationContext("/src/com/mj/xml/Bean.xml");
        BeanSay sa1 = (BeanSay) fileContext.getBean("BeanSay");
        sa1.setMsg("=Spring====");
        sa1.talk();

        ApplicationContext animalContext = new ClassPathXmlApplicationContext("com/mj/xml/Bean.xml");
        BeanAnimal ani =  (BeanAnimal) animalContext.getBean("Animal");
        ani.setAnimalName("dog");
        ani.showAnimal();

        BeanAnimal animal =  (BeanAnimal) animalContext.getBean("Animal");
        animal.setAnimalName("pig");
        animal.showAnimal();

        // init method   destroy method
        BeanLife life = (BeanLife) context.getBean("BeanLife");
        life.showName();

        //BeanDog 继承  BeanAnimal
        BeanDog dog = (BeanDog)context.getBean("BeanDog");
        dog.showAnimal();
        //加载多配置文件
        BeanUser user = (BeanUser)context.getBean("BeanUser");
        user.showUser();
        */

        ApplicationContext annotationCtx = new AnnotationConfigApplicationContext(BeanConfig.class);
        IBean beanPerson = (IBean) annotationCtx.getBean("beanPerson");
        beanPerson.show();

    }
}

BeanConfig.java

package com.mj.bean.annotation;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeanConfig {

    @Bean(name="beanPerson")
    public IBean beanPerson(){
        return new BeanPerson();
    }
}

IBean.java

package com.mj.bean.annotation;

public interface IBean {

    public  void show();
}

BeanPerson.java

package com.mj.bean.annotation;

public class BeanPerson implements IBean {
    private String cName = "BeanPerson";
    @Override
    public void show(){
        System.out.println( cName );
    }

    public void setcName(String cName) {
        this.cName = cName;
    }

}

运行

BeanPerson

你可能感兴趣的:(JAVA 核心笔记 || [xxx] Spring 之 JavaConfig 注解)