Spring-Common Notes and Role

1. Common Notes and Functions

1.1 @Configuration

Declare that the current class is a configuration class (equivalent to an xml file for a Spring configuration)

1.2 @ComponentScan

Automatically scan and register all classes using @Service,@Component,@Controller,@Repository under the specified package
Example:

@ComponentScan(value="com.atguigu",includeFilters = {
		@Filter(type=FilterType.ANNOTATION,classes={Controller.class}),
		@Filter(type=FilterType.ASSIGNABLE_TYPE,classes={BookService.class}),
		@Filter(type=FilterType.CUSTOM,classes={MyTypeFilter.class})
			},useDefaultFilters = false)	
//excludeFilters = Filter[]: Specify rules for excluding those components when scanning
 //includeFilters = Filter[]: Specify only which components to include when scanning,
useDefaultFilters = false needs to be set
 //FilterType.ANNOTATION: by comment
 //FilterType.ASSIGNABLE_TYPE: according to the given type;
//FilterType.ASPECTJ: Using ASPECTJ expressions
 //FilterType.REGEX: Specify using a regular
 //FilterType.CUSTOM: Use custom rules

1.3 @ComponentScans

Can contain more than one @ComponentScan
Example: @ComponentScans(value = {@ComponentScan,@ComponentScan,@ComponentScan})

1.4 @Lazy

Single-instance bean s: Objects are created by default at container startup;
Lazy Loading: Container startup does not create objects.Create an object with (get) Bean for the first time and initialize it;

1.5 @Conditional({Condition})

Example: @Conditional({WindowsCondition.class}), WindowsCondition is a class that implements the Condition interface
A bean can be defined on a class name or method name if it is registered in a container according to certain conditions.

1.6 Injection Component

How components are injected into containers
1 @Bean: Components that import third-party classes or packages
2.ComponentScan: Label annotations for package scan + components
3.@Import
4. Register using FactoryBean provided by Spring

1.6.1 @Import() Quick Import Component

Can import a single component or multiple components, id defaults to full class name
Example: @Import(value={Dog.class,Cat.class,MyImportSelector.class,MyImportBeanDefinitionRegistrar.class})

1.6.2. Use ImportSelector to customize components that need to be imported

ImportSelector is an interface defined by an array of strings containing the full class name of the component

//Custom logic returns components that need to be imported
public class MyImportSelector implements ImportSelector {

	//Return value is the full class name of the component imported into the container
	//AnnotationMetadata: All annotation information for the class currently labeled with the @Import annotation
	@Override
	public String[] selectImports(AnnotationMetadata importingClassMetadata) {
		// TODO Auto-generated method stub
		//importingClassMetadata
		//Method does not return null value, otherwise null pointer exception will be reported
		return new String[]{"com.bernard.bean.Blue","com.bernard.bean.Yellow"};
	}

}

1.6.3. Return custom components using ImportBeamDefinitionRegistrar

    public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

	/**
	 * AnnotationMetadata: Annotation information for the current class
	 * BeanDefinitionRegistry:BeanDefinition Register class;
	 * Add all the bean s you need to the container;
	 * Call BeanDefinitionRegistry.registerBeanDefinition to register manually
	 */
	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
		
		boolean definition = registry.containsBeanDefinition("com.atguigu.bean.Red");
		boolean definition2 = registry.containsBeanDefinition("com.atguigu.bean.Blue");
		if(definition && definition2){
			//Specify Bean Definition Information; (Bean type, Bean.)
			RootBeanDefinition beanDefinition = new RootBeanDefinition(RainBow.class);
			//Register a Bean, specify the bean name
			registry.registerBeanDefinition("rainBow", beanDefinition);
		}
	}

}

Test Class
Print out all bean s registered with the container

public class MyImportTest {
    @Test
    public void test01(){
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MyImportConfig.class);

        String[] beanDefinitionNames = annotationConfigApplicationContext.getBeanDefinitionNames();

        for (int i = 0; i < beanDefinitionNames.length; i++) {
            String beanDefinitionName = beanDefinitionNames[i];
            System.out.println(beanDefinitionName);
        }

    }
}

1.6.4. Use Factory Bean provided by Spring;

1) Get the object created by the factory bean calling getObject by default
2) To get the factory Bean itself, we need to precede the id with an &, e.g. "&colorFactoryBean"

//Create a Spring-defined FactoryBean
public class ColorFactoryBean implements FactoryBean<Color> {

	//Returns a Color object that is added to the container
	@Override
	public Color getObject() throws Exception {
		// TODO Auto-generated method stub
		System.out.println("ColorFactoryBean...getObject...");
		return new Color();
	}

	@Override
	public Class<?> getObjectType() {
		// TODO Auto-generated method stub
		return Color.class;
	}

	//Is it a singleton?
	//true: this bean is a single instance and holds a copy in a container
	//false: multiple instances, each fetch creates a new bean;
	@Override
	public boolean isSingleton() {
		// TODO Auto-generated method stub
		return false;
	}

}

Example registration:

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

Get an example

//Factory Bean gets the object created by calling getObject
Object bean2 = applicationContext.getBean("colorFactoryBean");//Get the bean returned by getObject
Object bean4 = applicationContext.getBean("&colorFactoryBean");//Get the factory bean itself

1.7 @Value

Use @Value to assign values to attribute fields
1. Basic Values
2. SpEL can be written; #{}
3. You can write ${}; take out the value in the configuration file [properties] (the value inside the running environment variable)

Configuration Class
Use @PropertySource to read k/v from an external configuration file and save it in a running environment variable;
Use ${} to fetch the value of the profile after loading the external profile

@PropertySource(value={"classpath:/person.properties"})
@Configuration
public class MainConfigOfPropertyValues {
	
	@Bean
	public Person person(){
		return new Person();
	}

}

bean

public class Person {
	@Value("Zhang San")
	private String name;

	@Value("#{20-2}")
	private Integer age;
	
	@Value("${person.nickName}")
	private String nickName;
}

1.8 @Autowired,@Resource,@Primary

  • The default priority is to find the corresponding component in the container by type: applicationContext.getBean(BookDao.class); assign values when found
  • If multiple components of the same type are found, then use the name of the property as the component id to find the applicationContext.getBean("bookDao") in the container.
  • The default for automatic assembly is to assign attributes well, and if no bean s exist in the injection container, you can use @Autowired(required=false);
  • @Qualifier("component id"): Use @Qualifier to specify the ID of the component that needs to be assembled, not the property name
  • @Primary: When Spring is auto-assembled, the preferred bean is used by default (in which case @Qualifier cannot be used when injecting components);
  • @Inject: Packages that need to be imported into javax.inject, as well as Autoired.There is no required=false function;
  • @Resource can be automatically assembled as @Autowired; it is assembled by component name by default; it does not support @Primary and @Autowired (reqiured=false) functions;

@Autowired: constructor, parameter, method, property; all get the value of the parameter component from the container

  • If @Autowired is labeled at the method/parameter position, Spring invokes this method to complete the assignment when it creates the current object, and the parameters used by the method are taken from the ioc container. By default, @Autowired works the same and can be assembled automatically
  • If @Autowired is labeled on a constructor: if a component has only one parameter constructor, the @Autowired with the parameter constructor can be omitted, or the component with the parameter location can be automatically retrieved from the container
  • If the @Bean labeled method creates an object, the value of the method parameter is obtained from the container

Supplement:
@Autowired:Spring defined;
@Resource, @Inject are both java specifications

1.9 @Profile

Specifies the environment in which a component can be registered in a container. Without specifying, the component can be registered in any environment

  • 1) Beans with an environment identifier can only be registered in the container if the environment is activated.Default is default environment
  • 2) Written on the configuration class, all configurations within the entire configuration class will not take effect until the specified environment
  • 3) Beans without environment labels are loaded in any environment;
    Java configuration MainConfigOfProfile.java
@PropertySource("classpath:/dbconfig.properties")
@Configuration
public class MainConfigOfProfile implements EmbeddedValueResolverAware{
	
	@Value("${db.user}")
	private String user;
	
	private StringValueResolver valueResolver;
	
	private String  driverClass;
	
	@Bean
	public Yellow yellow(){
		return new Yellow();
	}
	
	@Profile("test")
	@Bean("testDataSource")
	public DataSource dataSourceTest(@Value("${db.password}")String pwd) throws Exception{
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		dataSource.setUser(user);
		dataSource.setPassword(pwd);
		dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
		dataSource.setDriverClass(driverClass);
		return dataSource;
	}
	
	@Profile("dev")
	@Bean("devDataSource")
	public DataSource dataSourceDev(@Value("${db.password}")String pwd) throws Exception{
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		dataSource.setUser(user);
		dataSource.setPassword(pwd);
		dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/ssm_crud");
		dataSource.setDriverClass(driverClass);
		return dataSource;
	}
	
	@Profile("prod")
	@Bean("prodDataSource")
	public DataSource dataSourceProd(@Value("${db.password}")String pwd) throws Exception{
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		dataSource.setUser(user);
		dataSource.setPassword(pwd);
		dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/scw_0515");
		
		dataSource.setDriverClass(driverClass);
		return dataSource;
	}

	@Override
	public void setEmbeddedValueResolver(StringValueResolver resolver) {
		// TODO Auto-generated method stub
		this.valueResolver = resolver;
		driverClass = valueResolver.resolveStringValue("${db.driverClass}");
	}

}

Activation method:

  • 1. Use command action dynamic parameters: load-Dspring.profiles.active=test at the virtual machine parameter location
  • 2. Activate an environment by java code in four steps
    • 1) Create an applicationContext
    • 2) Set the environment that needs to be activated
    • 3) Register Master Configuration Class
    • 4) Start refresh container

Activate test code

public void test01(){
	AnnotationConfigApplicationContext applicationContext =
			new AnnotationConfigApplicationContext();
	//1. Create an applicationContext
	//2. Set up an environment that needs to be activated
	applicationContext.getEnvironment().setActiveProfiles("dev");
	//3. Register the main configuration class
	applicationContext.register(MainConfigOfProfile.class);
	//4. Start Refresh Container
	applicationContext.refresh();


	String[] namesForType = applicationContext.getBeanNamesForType(DataSource.class);
	for (String string : namesForType) {
		System.out.println(string);
	}

	Yellow bean = applicationContext.getBean(Yellow.class);
	System.out.println(bean);
	applicationContext.close();
}

1.11 @Scope

When registering bean s, spring defaults to single-instance, scope="singleton". In addition, common scopes include prototype, request, session scopes

  • prototype: multi-instance: the ioc container startup does not call the method to create the object in the container.
  • Request: create an instance of the same request
  • Session: Create an instance of the same session

Tags: Spring Java JDBC MySQL

Posted on Thu, 08 Aug 2019 18:46:04 -0700 by grungefreak