Spring注解驱动开发

2019-03-06 07:15:42来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

1 组件注册

1.1 @Configuration&@Bean注册Bean

1.1.1 传统的xml方式

  • Person.java
package com.xuweiwei.spring.model;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Person {
    private String name;
    private Integer age;

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
View Code
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    
    <bean id="person" class="com.xuweiwei.spring.model.Person">
        <property name="name" value="许威威"/>
        <property name="age" value="27"/>
    </bean>

</beans>
  • 测试
package com.xuweiwei.sping;

import com.xuweiwei.spring.model.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:applicationContext.xml")
public class SpringTest {
    @Autowired
    private Person person;


    @Test
    public void test(){
        System.out.println(person);
    }

}
View Code

1.1.2 注解方式

  • Person.java
package com.xuweiwei.spring.model;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Person {
    private String name;
    private Integer age;

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
View Code
  • MainConfig.java
package com.xuweiwei.spring.config;

import com.xuweiwei.spring.model.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
//配置类==配置文件
//告诉Spring这是一个配置类
@Configuration //相当于applicationContext.xml
public class MainConfig {

    /**
     * @Bean 注解相当于bean标签
     *
     * @return
     */
    @Bean
    public Person person() {
        return new Person("许威威", 27);
    }

}
  • 测试
package com.xuweiwei.sping;

import com.xuweiwei.spring.config.MainConfig;
import com.xuweiwei.spring.model.Person;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ConfigurationSpringTest {

    @Test
    public void test() {
        ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);

        Person person = context.getBean(Person.class);
        System.out.println(person);

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

    }

}
View Code

1.2 @ComponentScan自动扫描

1.2.1 传统的xml方式

  • PersonController.java
package com.xuweiwei.spring.controller;

import org.springframework.stereotype.Controller;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
@Controller
public class PersonController {
}
View Code
  • PersonService.java
package com.xuweiwei.spring.service;

import org.springframework.stereotype.Service;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
@Service
public class PersonService {
}
View Code
  • PersonDao.java
package com.xuweiwei.spring.dao;

import org.springframework.stereotype.Repository;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
@Repository
public class PersonDao {
}
View Code
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    <!--只要标注了@Controller、@Service、@Component、@Repository注解的都会自动注入到IOC容器中-->
    <context:component-scan base-package="com.xuweiwei.spring"></context:component-scan>
</beans>
  • 测试
package com.xuweiwei.sping;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:applicationContext.xml")
public class SpringTest {
    @Autowired
    private ApplicationContext context;

    @Test
    public void test(){
        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }
    }
}
View Code

1.2.2 注解方式

  • Person.java
package com.xuweiwei.spring.model;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Person {
    private String name;
    private Integer age;

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
View Code
  • PersonDao.java
package com.xuweiwei.spring.dao;

import org.springframework.stereotype.Repository;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
@Repository
public class PersonDao {
}
View Code
  • PersonService.java
package com.xuweiwei.spring.service;

import org.springframework.stereotype.Service;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
@Service
public class PersonService {
}
View Code
  • PersonController.java
package com.xuweiwei.spring.controller;

import org.springframework.stereotype.Controller;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
@Controller
public class PersonController {
}
View Code
  • MainConfig.java
package com.xuweiwei.spring.config;

import com.xuweiwei.spring.model.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
//配置类==配置文件
//告诉Spring这是一个配置类
@Configuration //相当于applicationContext.xml
@ComponentScan(value = "com.xuweiwei")
public class MainConfig {

    /**
     * @Bean 注解相当于bean标签
     *
     * @return
     */
    @Bean
    public Person person() {
        return new Person("许威威", 27);
    }

}
  • 测试
package com.xuweiwei.sping;

import com.xuweiwei.spring.config.MainConfig;
import com.xuweiwei.spring.model.Person;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ConfigurationSpringTest {

    @Test
    public void test() {
        ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);

        Person person = context.getBean(Person.class);
        System.out.println(person);

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

    }

}
View Code

 

  • 如果是xml方式的只过滤Controller注解标注的类,代码如下
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    <!--只要标注了@Controller、@Service、@Component、@Repository注解的都会自动注入到IOC容器中,默认扫描全部-->
    <context:component-scan base-package="com.xuweiwei.spring" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>
  • 如果是注解方式只过滤Controller注解标注的类,代码如下
package com.xuweiwei.spring.config;

import com.xuweiwei.spring.model.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
//配置类==配置文件
//告诉Spring这是一个配置类
@Configuration //相当于applicationContext.xml
@ComponentScan(
        value = "com.xuweiwei",
        useDefaultFilters = false,
        includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Controller.class)}
)
public class MainConfig {

    /**
     * @return
     * @Bean 注解相当于bean标签
     */
    @Bean
    public Person person() {
        return new Person("许威威", 27);
    }

}

1.3 @Scope注解

  • 设置组件的作用域。

 

  • 示例:
    • MainConfig.java  
package com.xuweiwei.spring.config;

import com.xuweiwei.spring.model.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
//配置类==配置文件
//告诉Spring这是一个配置类
@Configuration //相当于applicationContext.xml
public class MainConfig {
    /**
     * * @see ConfigurableBeanFactory#SCOPE_PROTOTYPE
     * * @see ConfigurableBeanFactory#SCOPE_SINGLETON
     * * @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST
     * * @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION
     * 默认情况下,是singleton
     *
     * singleton是单例
     * prototype是多例
     * request同一次请求创建一个实例
     * session同一个Session创建一个实例
     * @return
     */
    @Scope(value = "singleton")
    @Bean
    public Person person() {
        return new Person("许威威", 27);
    }

}
    • 测试  
package com.xuweiwei.sping;

import com.xuweiwei.spring.config.MainConfig;
import com.xuweiwei.spring.model.Person;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ConfigurationSpringTest {

    @Test
    public void test() {
        ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);

        Person person1 = context.getBean(Person.class);
        Person person2 = context.getBean(Person.class);
        System.out.println(person1 == person2);
    }

}
View Code

 

  • 默认情况下,IOC容器启动会调用方法并创建对象放入到容器中,以后每次获取直接从容器中获取。
  • 如果scope的值是prototype,那么IOC容器启动的时候并不会调用方法,而是每次获取对象的时候创建对象并将对象放入到容器中。

1.4 @Lazy注解

  • @Lazy针对的是单实例的Bean。

 

  • 示例:
package com.xuweiwei.spring.config;

import com.xuweiwei.spring.model.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
//配置类==配置文件
//告诉Spring这是一个配置类
@Configuration //相当于applicationContext.xml
public class MainConfig {
    /**
     * 懒加载:容器启动的时候不创建对象,而是在第一次使用的时候,才创建对象
     * @return
     */
    @Lazy
    @Bean
    public Person person() {
        System.out.println("给容器中注入Bean^_^ ^_^ ^_^ ^_^");
        return new Person("许威威", 27);
    }

}

1.5 @Conditional注解

  • 根据条件给容器中注入Bean。【SpringBoot底层大量使用了这个注解】

 

  • 示例:
    • LinuxCondition.java  
package com.xuweiwei.spring.condition;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class LinuxCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment environment = context.getEnvironment();
        String property = environment.getProperty("os.name");

        if(property.contains("linux")){
            return true;
        }
        return false;
    }
}
    • WindowsCondition.java  
package com.xuweiwei.spring.condition;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class WindowsCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment environment = context.getEnvironment();
        String property = environment.getProperty("os.name");

        if(property.contains("Windows")){
            return true;
        }
        return false;
    }
}
    • MainConfig2.java  
package com.xuweiwei.spring.config;

import com.xuweiwei.spring.condition.LinuxCondition;
import com.xuweiwei.spring.condition.WindowsCondition;
import com.xuweiwei.spring.model.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
@Configuration
public class MainConfig2 {

    @Conditional(value = WindowsCondition.class)
    @Bean("bill")
    public Person person1(){
        return new Person("比尔盖茨",60);
    }

    @Conditional(value = LinuxCondition.class)
    @Bean("linus")
    public Person person2(){
        return new Person("林纳斯",50);
    }

}
    • 测试  
package com.xuweiwei.sping;

import com.xuweiwei.spring.config.MainConfig2;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ConfigurationSpringTest {

    @Test
    public void test() {
        ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig2.class);
        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }
    }

}
View Code

 

  • 【注】:如果@Conditional注解标注在类上,表示满足当前条件,这个类配置的所有Bean注册才能生效。

1.6 @Import注解

  • 给容器中快速导入一个组件。

 

  • ①@Import(要导入容器的组件):容器就会自动注册这个组件。
  • 示例:
    • Color.java  
package com.xuweiwei.spring.model;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Color {
}
View Code
    • Person.java  
package com.xuweiwei.spring.model;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Person {
    private String name;
    private Integer age;

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
View Code
    • MainConfig.java  
package com.xuweiwei.spring.config;

import com.xuweiwei.spring.model.Color;
import com.xuweiwei.spring.model.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Lazy;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
//配置类==配置文件
//告诉Spring这是一个配置类
@Import(value = Color.class)
@Configuration //相当于applicationContext.xml
public class MainConfig {
    /**
     * 懒加载:容器启动的时候不创建对象,而是在第一次使用的时候,才创建对象
     * @return
     */
    @Lazy
    @Bean
    public Person person() {
        System.out.println("给容器中注入Bean^_^ ^_^ ^_^ ^_^");
        return new Person("许威威", 27);
    }

}
    • 测试  
package com.xuweiwei.sping;

import com.xuweiwei.spring.config.MainConfig;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ConfigurationSpringTest {

    @Test
    public void test() {
        ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }
    }

}
View Code

 

  • ②使用ImportSelector:返回需要导入组件的全类名数组。
  • 示例:
    • Color.java  
package com.xuweiwei.spring.model;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Color {
}
View Code
    • Red.java  
package com.xuweiwei.spring.model;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Red {
}
View Code
    • Blue.java  
package com.xuweiwei.spring.model;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Blue {
}
View Code
    • Person.java  
package com.xuweiwei.spring.model;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Person {
    private String name;
    private Integer age;

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
View Code
    • MyImportSelector.java
package com.xuweiwei.spring.condition;

import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.type.AnnotationMetadata;

/**
 * @describe: 自定义逻辑返回需要导入的组件
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class MyImportSelector implements ImportSelector {
    /**
     * 返回值就是要导入到容器中的组件全类名
     * @param importingClassMetadata 当前标注@Import注解的类的所有注解信息
     * @return
     */
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {

        return new String[]{"com.xuweiwei.spring.model.Blue","com.xuweiwei.spring.model.Red"};
    }
}
    • MainConfig.java  
package com.xuweiwei.spring.config;

import com.xuweiwei.spring.condition.MyImportSelector;
import com.xuweiwei.spring.model.Color;
import com.xuweiwei.spring.model.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Lazy;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
//配置类==配置文件
//告诉Spring这是一个配置类
@Import(value = {Color.class, MyImportSelector.class})
@Configuration //相当于applicationContext.xml
public class MainConfig {
    /**
     * 懒加载:容器启动的时候不创建对象,而是在第一次使用的时候,才创建对象
     * @return
     */
    @Lazy
    @Bean
    public Person person() {
        System.out.println("给容器中注入Bean^_^ ^_^ ^_^ ^_^");
        return new Person("许威威", 27);
    }

}
    • 测试  
package com.xuweiwei.sping;

import com.xuweiwei.spring.config.MainConfig;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ConfigurationSpringTest {

    @Test
    public void test() {
        ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }
    }

}
View Code

 

  • ③使用ImportBeanDefinitionRegistrar:可以手动注册指定名称的Bean。
  • 示例:
    • Blue.java  
package com.xuweiwei.spring.model;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Blue {
}
View Code
    • Color.java  
package com.xuweiwei.spring.model;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Color {
}
View Code
    • Person.java  
package com.xuweiwei.spring.model;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Person {
    private String name;
    private Integer age;

    public Person() {
    }

    public Person(String name, Integer age) {
        this.name = name;
        this.age = age;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
View Code
    • Red.java  
package com.xuweiwei.spring.model;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Red {
}
View Code
    • White.java  
package com.xuweiwei.spring.model;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class White {
}
View Code
    • MyImportBeanDefinitionRegistrar.java  
package com.xuweiwei.spring.condition;

import com.xuweiwei.spring.model.White;
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;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    /**
     * @param importingClassMetadata:当前标注@Import注解的类的所有注解信息
     * @param registry:BeanDefinition注册类
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        boolean flag = registry.containsBeanDefinition("white");
        if (!flag) {
            registry.registerBeanDefinition("white", new RootBeanDefinition(White.class));
        }
    }
}
    • MainConfig.java
package com.xuweiwei.spring.config;

import com.xuweiwei.spring.condition.MyImportBeanDefinitionRegistrar;
import com.xuweiwei.spring.condition.MyImportSelector;
import com.xuweiwei.spring.model.Color;
import com.xuweiwei.spring.model.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Lazy;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
//配置类==配置文件
//告诉Spring这是一个配置类
@Import(value = {Color.class, MyImportSelector.class, MyImportBeanDefinitionRegistrar.class})
@Configuration //相当于applicationContext.xml
public class MainConfig {
    /**
     * 懒加载:容器启动的时候不创建对象,而是在第一次使用的时候,才创建对象
     * @return
     */
    @Lazy
    @Bean
    public Person person() {
        System.out.println("给容器中注入Bean^_^ ^_^ ^_^ ^_^");
        return new Person("许威威", 27);
    }

}
    • 测试  
package com.xuweiwei.sping;

import com.xuweiwei.spring.config.MainConfig;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ConfigurationSpringTest {

    @Test
    public void test() {
        ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }
    }

}
View Code

1.7 使用FactoryBean注册Bean

  • 示例:
    • ColorFactoryBean.java  
package com.xuweiwei.spring.model;

import org.springframework.beans.factory.FactoryBean;

/**
 * @describe: 创建Spring提供的FactoryBean
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class ColorFactoryBean implements FactoryBean<Color> {
    /**
     * 返回一个Color对象,这个对象会添加到容器中
     * @return
     * @throws Exception
     */
    @Override
    public Color getObject() throws Exception {
        return new Color();
    }

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

    @Override
    public boolean isSingleton() {
        return true;
    }
}
    • MainConfig.java  
package com.xuweiwei.spring.config;

import com.xuweiwei.spring.model.ColorFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
//配置类==配置文件
//告诉Spring这是一个配置类
@Configuration //相当于applicationContext.xml
public class MainConfig {

    @Bean
    public ColorFactoryBean colorFactoryBean(){
        return new ColorFactoryBean();
    }


}
    • 测试  
package com.xuweiwei.sping;

import com.xuweiwei.spring.config.MainConfig;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ConfigurationSpringTest {

    @Test
    public void test() {
        ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class);
        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }
    }

}
View Code

 

2 生命周期

2.1 @Bean指定初始化方法和销毁方法

  •  示例:
    • Car.java  
package com.xuweiwei.spring.model;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Car {

    public Car() {
        System.out.println("构造方法被调用了O(∩_∩)O哈哈~");
    }

    public void init() {
        System.out.println("初始化了^_^");
    }

    public void destroy() {
        System.out.println("销毁了o(╥﹏╥)o");
    }
}
    • MainConfig3.java  
package com.xuweiwei.spring.config;

import com.xuweiwei.spring.model.Car;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
@Configuration
public class MainConfig3 {

    @Bean(initMethod = "init",destroyMethod = "destroy")
    public Car car(){
        return new Car();
    }

}
    • 测试  
package com.xuweiwei.sping;

import com.xuweiwei.spring.config.MainConfig3;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ConfigurationSpringTest {

    @Test
    public void test() {
        ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig3.class);
        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }

        ((AnnotationConfigApplicationContext) context).close();
    }

}
View Code

2.2 让Bean实现InitializingBean和DisposableBean接口

  •  示例:
    • Car.java  
package com.xuweiwei.spring.model;

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

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Car implements InitializingBean, DisposableBean {

    public Car() {
        System.out.println("构造方法被调用了O(∩_∩)O哈哈~");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("销毁");
    }
}
    • MainConfig3.java  
package com.xuweiwei.spring.config;

import com.xuweiwei.spring.model.Car;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
@Configuration
public class MainConfig3 {

    @Bean
    public Car car(){
        return new Car();
    }

}
    • 测试  
package com.xuweiwei.sping;

import com.xuweiwei.spring.config.MainConfig3;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ConfigurationSpringTest {

    @Test
    public void test() {
        ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig3.class);
        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }

        ((AnnotationConfigApplicationContext) context).close();
    }

}
View Code

2.3 @PostConstruct和@PreDestroy注解

  • 示例:
    • Car.java  
package com.xuweiwei.spring.model;

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

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Car {

    public Car() {
        System.out.println("构造方法被调用了O(∩_∩)O哈哈~");
    }

    @PostConstruct
    public void init() {
        System.out.println("初始化");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("销毁");
    }
}
    • MainConfig3.java  
package com.xuweiwei.spring.config;

import com.xuweiwei.spring.model.Car;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
@Configuration
public class MainConfig3 {

    @Bean
    public Car car(){
        return new Car();
    }

}
    • 测试  
package com.xuweiwei.sping;

import com.xuweiwei.spring.config.MainConfig3;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ConfigurationSpringTest {

    @Test
    public void test() {
        ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig3.class);
        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }

        ((AnnotationConfigApplicationContext) context).close();
    }

}
View Code

2.4 让Bean实现BeanPostProcessor(后置处理器)

  • 在Bean初始化前后进行一些工作。

 

  • 示例:
    • Car.java  
package com.xuweiwei.spring.model;

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

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
public class Car {

    public Car() {
        System.out.println("构造方法被调用了O(∩_∩)O哈哈~");
    }

    @PostConstruct
    public void init() {
        System.out.println("初始化");
    }

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

}
    • MyBeanPostProcessor.java  
package com.xuweiwei.spring.model;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("在初始化之前bean:" + bean);
        System.out.println("在初始化之前beanName:" + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("在初始化之后bean:" + bean);
        System.out.println("在初始化之后beanName:" + beanName);
        return bean;
    }
}
    • MainConfig3.java  
package com.xuweiwei.spring.config;

import com.xuweiwei.spring.model.Car;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * @describe:
 * @author: 不为往事扰,余生只爱笑。
 * @version: 1.0
 */
@ComponentScan(value = "com.xuweiwei")
@Configuration
public class MainConfig3 {

    @Bean
    public Car car(){
        return new Car();
    }

}
    • 测试  
package com.xuweiwei.sping;

import com.xuweiwei.spring.config.MainConfig3;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class ConfigurationSpringTest {

    @Test
    public void test() {
        ApplicationContext context = new AnnotationConfigApplicationContext(MainConfig3.class);
        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            System.out.println(name);
        }

        ((AnnotationConfigApplicationContext) context).close();
    }

}
View Code

 

3 属性赋值

 


原文链接:https://www.cnblogs.com/xuweiweiwoaini/p/10479717.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:(高并发)防止重复点击,屏蔽多次无效请求的解决方案(优惠劵被

下一篇:2019年-寒假 Java入门-尚学堂-马士兵讲师-课堂笔记