敲代码的帅boy
Spring 学习代码笔记

MyConfig类(配置类)


import	java.lang.annotation.Inherited;


import cn.blackui.condition.EnergyCondition;
import cn.blackui.condition.OilCondition;
import cn.blackui.entity.*;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.annotation.*;

@Configuration
//@Import({Apple.class,Banana.class})/* 该种为直接方法:::此时获取的该些bean的name即id为全类名*/
//@Import( {Orange.class,MyimportSelector.class, })/*@Import注解的第二种方法*/
//@Import( {MyImportBeanDefinitionRegistrar.class})/* @Import注解的第三种方法*/
    @ComponentScan(value ="cn.blackui")

public class MyConfig  {
    /*使用注解来存bean,需要一个带有@@Configuration的配置类*/
   // @Bean(value ="mystudent",initMethod = "myInit",destroyMethod = "myDestroy")/*通过bean注解来实现注解形式的存bean*/
    //@Scope("singleton")/*bean的作用域:单例:singleton,多例:prototype*/
      //  @Lazy/* 加一个lazy注解,可以延迟加载,单例在初始化时创建对象,延迟到在创建第一个getbean()时产生*/

    @Bean(value = "student")
    public Student myStudent( ){
        System.out.println("##########");
        Student student = new Student("zs10",10,"18");
//        Address address = new Address("xa02","bj02")
        return student;
    }
//    @Bean
//    public Address address1(){
//        Address address = new Address("xa02","bj02") ;
//        return address ;
//    }

//
//
//    @Bean
//    @Conditional(OilCondition.class)        /*给定条件判断什么时候加入*/
//    public Car OilCar(){
//
//        return new OilCar();
//    }
//    @Bean
//    @Conditional(EnergyCondition.class)     /*给定条件判断什么时候加入*/
//    public  Car EnergyCar(){
//
//        return new EnergyCar();
//    }
//
//    @Bean
//    public FactoryBean<Apple> myfactorybean(){
//        return new MyFactoryBean();//到底是什么? 是MyFactoryBean?还是Apple??怎么区分??????????
//        //可以通过符号&来区分:
//        //不加&:得到的是Apple,是工厂创建的实例Apple
//        //加&:得到的是MyFactoryBean
//
//    }


}


MyFactoryBean

/*
* 工厂bean:
* 通过:实现接口FactoryBean来重写方法,获取具体的bean
* 通过在配置类中@bean+返回值
*
* 通过&来区分是拿MyFactoryBean还是工厂实现的实例apple
* 不加拿的是实例Apple
* 加拿的是工厂MyFactioryBean
*
*
* */
import cn.blackui.entity.Apple;
import org.springframework.beans.factory.FactoryBean;

public class MyFactoryBean implements FactoryBean {
    @Override
    public Object getObject() throws Exception {
        return new Apple();
    }

    @Override
    public Class<?> getObjectType() {
        return Apple.class;//Apple
    }

    @Override
    public boolean isSingleton() {
        return  true;
    }
}

MyImportBeanDefinitionRegistrar

/*
* @Import注解的第三种方式
* 通过实现ImportBeanDefinitionRegistrar接口的类
* 通过registerBeanDefinitions()中的参数:BeanDefinitionRegistry  beanDefinitionRegistry来加入我们的bean
* 用到.registerBeanDefinition(String var1, BeanDefinition var2)方法
* 注意::在使用时由于需要BeanDefinition类型
* BeanDefinition是个接口类他的实现类:RootBeanDefinition来进行转型
*
*
*

* */

import cn.blackui.entity.Orange;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    //BeanDefinitionRegistry:bean的定义注册信息,他能拿到我们bean的所有信息,那么我们可以直接将bean注册到这个里面就可以了
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {

        //"cn.blackui.entity.Orange"
        //在 void registerBeanDefinition(String var1, BeanDefinition var2)中参数必须一致,所以需要将要加入的类名.class
        //转成beanDefinition型,所以用BeanDefinition这个接口的实现类RootBeanDefinition new个对象为beanDefinition型
        //点进去查看RootBeanDefinition类有class型string型都可以用::
            BeanDefinition beanDefinition= new RootBeanDefinition(Orange.class);
        //  BeanDefinition beanDefinition= new RootBeanDefinition("cn.blackui.entity.Orange");
        beanDefinitionRegistry.registerBeanDefinition("myorange",beanDefinition);//id class

    }
}


MyimportSelector

/*
Import注解第二种方法:
* 通过自定义ImportSelector接口的实现类,实现selectImports()方法
直接在方法中的返回值中加入要加入IOC容器的Bean的全类名
还要
通过@Import({接口实现类的名字.class})
告诉程序自己编写的实现类
*
*
*
* */
import cn.blackui.entity.Apple;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;

public class MyimportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {


        return new String[]{"cn.blackui.entity.Apple","cn.blackui.entity.Banana"};  //返回值就是要加入IOC容器的bean全类名
    }
}


MyFunction

/*
* 只需要实现InitializingBean中的afterPropertiesSet()来 初始化
* 通过DisposableBean的destroy()来销毁
*
*
 *
* */

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;






@Component
public class MyFunction implements InitializingBean , DisposableBean {

    public void myMethod(){



    }



    @Override
    public void afterPropertiesSet() throws Exception {




        System.out.println("初始化.....afterPropertiesSet()");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("销毁.......destroy()");
    }
}


MyIntToStringConverter



import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/*
* 通过JAVA规范
* 三层注解的形式:@component
* @PostConstruct相当于@Bean+返回值方式的init
* @PreDestroy相当于相当于@Bean+返回值方式的destory
* */
@Component(value="myConterver")
public class MyIntToStringConverter {


    @PostConstruct
    public void Init(){
        System.out.println("转换.....init...");
    }



            public void myConterver(){
                System.out.println("......转换..........");


}

    @PreDestroy
public  void Destory() {

    System.out.println("转换.....Destory...");

}


}


MyXXX


import cn.blackui.entity.Student;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

@Controller
public class MyXXX implements BeanPostProcessor {


//拦截器
    @Override
    public Object postProcessBeforeInitialization(Object Bean, String BeanName) throws BeansException {

        System.out.println("初始化:"+BeanName+":"+Bean);
        System.out.println("初始化.........");
        System.out.println("######################");

                /*通过下面代码能够将该拦截器拦截到的bean进行赋值操作
                *
                *
                * */
        if (Bean instanceof Student){
            Student stu=(Student)Bean;
            stu.setStuName(":gzk");
            stu.setStuNo(10086);
            return stu;

        }




        /*  在返回值为null的时候,打印出来的是全为初始化
        * 当给他一个返回值的时候,就能够打印出来销毁方法
        * */
        return Bean;
    }






    @Override
    public Object postProcessAfterInitialization(Object Bean, String BeanName) throws BeansException {

        System.out.println("销毁:"+BeanName+":"+Bean);
        System.out.println("销毁、、.....");


        return Bean;
    }
}


TestStudent(测试类)


import cn.blackui.config.MyConfig;
import cn.blackui.config.MyFactoryBean;

import cn.blackui.converter.MyIntToStringConverter;
import cn.blackui.entity.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestStudent {
public static void TestXml(){
 ApplicationContext context
        = new ClassPathXmlApplicationContext("applicationContext.xml");
        //2.从IOC容器中获取Bean实例(id为"student"的Student对象)
        /*getBeanDefinitionNames()方法的返回值为:Spring 容器中所有 JavaBean 的名称,返回类型是一个字符串数组。*/
//           String[]  beanDefinitionNames = context.getBeanDefinitionNames();
//               for (String name: beanDefinitionNames ){
//
//                   System.out.println(name);
//           }

    //bean类的销毁
   //( (ClassPathXmlApplicationContext)context).close();





    /*通过getBean方法的id值去获取bean的实例*/
//      Student stu=(Student)context.getBean("student" );
//           System.out.println(stu);
//    Student stu1=(Student)context.getBean("student");
//    Student stu2=(Student)context.getBean("student" );
//   System.out.println(stu1==stu2);


}









//注解形式
    public static void TestAnnotation() {
System.out.println("************");

    ApplicationContext context
            = new AnnotationConfigApplicationContext(MyConfig.class);
        /*getBeanDefinitionNames()方法的返回值为:Spring 容器中所有 JavaBean 的名称,返回类型是一个字符串数组。*/


// 通过@compoment加value值和方法名一样来将该方法拿到context.getBean("value"),直接调用该方法
//        MyIntToStringConverter converter=(MyIntToStringConverter)context.getBean("myConterver");
//        converter.myConterver();

//
//        String[]  beanDefinitionNames = context.getBeanDefinitionNames();
//        for (String name: beanDefinitionNames ){
//
//            System.out.println(name);
//        }

    //工厂bean
//        Object obj= context.getBean("myfactorybean");
//        System.out.println(obj);




        Student stu=(Student)context.getBean("student" );
        System.out.println(stu);

//                 Student stu3=(Student)context.getBean(Student.class);
//                 Student stu4=(Student)context.getBean(Student.class);
//
//        System.out.println(stu3==stu4);

      ((AnnotationConfigApplicationContext)context).close();

    }






    public static void main(String[] args) {
           // TestXml();
             TestAnnotation();
    }


}


applicationContext.xml(XML配置文件)

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 框架在生成对象时,需要使用无参构造-->
    <!--控制反转IoC、 依赖注入DI-->
    <!--通过p标签赋值 -->
    <!--<bean id="student" class="cn.blackui.entity.Student" p:stuNo="100" p:stuName="xx" p:stuAge="33" >-->
    <!--scope是对于单例与多实例的属性:singleton,prototype,默认是单实例-->
    <bean id="student" class="cn.blackui.entity.Student" scope="singleton" init-method="myInit" destroy-method="myDestroy" >
        <!--value:简单类型-->
        <property name="stuNo" value="1"></property>
        <property name="stuName" value="张三"></property>
        <property name="stuAge" value="23"></property>
        <!--ref:其他类型-->
        <property name="address" ref="myAddress"></property>

        <!-- 构造方法-
        <constructor-arg value="aa" name="stuName" ></constructor-arg>
        <constructor-arg value="1" name="stuNo" ></constructor-arg>
        <constructor-arg value="33" name="stuAge"></constructor-arg>
        -->
    </bean>
   <bean id="myAddress" class="cn.blackui.entity.Address">
        <property name="homeAddress" value="jining"></property>
        <property name="schoolAddress" value="taian"></property>
   </bean>

    <!--<bean id="myaddress" class="cn.blackui.entity.Address">-->
    <!--<property name="homeAddrss" value="xa"></property>-->
    <!--<property name="schoolAddrss" value="bj"></property>-->
    <!--</bean>-->





</beans>

Student




public class Student {
    //私有属性
        private  String stuName;
        private int stuNo;
        private String stuAge;
        private Address address;
        //Student的无参构造
    public Student() {
        System.out.println("无参构造");
    }
//属性所对应的set与get方法
    public void setStuNo(int stuNo) {
        this.stuNo= stuNo;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }



    public void setStuAge(String stuAge) {
        this.stuAge=stuAge;

    }

    public String getStuName() {
        return stuName;
    }

    public int getStuNo() {
        return stuNo;
    }

    public String getStuAge() {
        return stuAge;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public Address getAddress() {
        return address;
    }

    //两个方法
    private void myInit() {
        System.out.println("init........");
    }
    private void myDestroy() {
        System.out.println("Destory........");
    }

    //Student的有参构造
    public Student(String stuName, int stuNo, String stuAge, Address address) {

        this.stuName = stuName;
        this.stuNo = stuNo;
        this.stuAge = stuAge;
        this.address = address;
        System.out.println("4有参构造");
    }
    public Student(String stuName, int stuNo, String stuAge) {
        System.out.println("进行了3有参构造!");
        this.stuName = stuName;
        this.stuNo = stuNo;
        this.stuAge = stuAge;

    }
//重写ToString方法,去打印一个对象。
    @Override
    public String toString() {
        return "Student{" +
                "stuName='" + stuName + '\'' +
                ", stuNo=" + stuNo +
                ", stuAge='" + stuAge + '\'' +'\'' +
                ", address='"+address+'\'' +'\''+
                '}';
    }


}


++Address,Apple,Banana,Car,EnergyCar,OilCar,Orange, 等类未写入!!!!!!!!!!!! 后续添加............ ++