Spring annotation driven development (c) automatically assembling -----

Automated assembly

concept

Spring using dependency injection (DI), to complete the assembly of each vessel IOC dependencies assignment.

@Autowired ----- automatic injection

1, find the corresponding default priority according to the type of component to the container

applicationContext.getBean(BookDao.class);

Found on assignment

2, if a plurality of components of the same type is found, then the property name as the id to find a container assembly

applicationContext.getBean("bookDao");

3、@Qualifier("bookDao")

Use @Qualifier id specified component assembly required, instead of using the property name.

4, automatic assembly be sure to attribute the default assignment is good, no error will be

You may be used @Autowired (required = false);

5、@Primary

Let Spring for automatic assembly when the default choice of bean; can continue to use @Qualifier need to specify the name of the assembly of the bean.

Injection Example:

BookService{
    @Autowired
    BookDao bookDao;
}

@Resource & @Inject ----- Spring supports @Resource (JSR250) and @Inject (JSR330) [java specification comments]

@Resource

@Autowired and can function as automatic assembly; default is assembled according to the component name; @Primary no support function is not supported @Autowired (reqiured = false);

@Inject

You need to import javax.inject packages, and Autowired function the same. Not required = false the function;

Note: @Autowired: the Spring-defined; @ Resource, @ Inject all java specification

package com.atguigu.service;


import javax.annotation.Resource;
import javax.inject.Inject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.atguigu.dao.BookDao;


@Service
public class BookService {
    
    //@Qualifier("bookDao")
    //@Autowired(required=false)
    //@Resource(name="bookDao2")
    @Inject
    private BookDao bookDao;
    
    public void print(){
        System.out.println(bookDao);
    }

    @Override
    public String toString() {
        return "BookService [bookDao=" + bookDao + "]";
    }
}

Principle : AutowiredAnnotationBeanPostProcessor: autowire parsed;

Method, the configuration of the position of the automatic assembly ----- @ Autowired

[Method marked position] ----- @ Bean + method parameter; parameter acquisition from the container; default does not write @Autowired effect is the same; automatic assembly can be

Package Penalty for com.atguigu.bean; 

Import org.springframework.beans.factory.annotation.Autowired;
 Import org.springframework.stereotype.Component; 

// default added to the ioc container components, container starts will call no-argument constructor to create an object , then operations such as initializing the assignment 
@Component
 public  class Boss { 
        
    Private Car CAR;
  public Car getCar () {
         return CAR; 
    } 

    @Autowired 
    // marked in the method, Spring container creates the current object, the method is called, to complete the assignment;
     / / parameters of the method used, the type of custom value acquired from the container ioc 
    public  void setCar (Car CAR) {
         the this .car = CAR; 
    } 

    @Override
    public String toString() {
        return "Boss [car=" + car + "]";
    }
}

[Marked on the constructor] ----- If the component is only a constructor parameter, this parameter has @Autowired constructor may be omitted, or the position of the component parameters may be automatically acquired from the vessel

Package Penalty for com.atguigu.bean; 

Import org.springframework.beans.factory.annotation.Autowired;
 Import org.springframework.stereotype.Component; 

// default added to the ioc container components, container starts will call no-argument constructor to create an object , then operations such as initializing the assignment 
@Component
 public  class Boss { 
        
    Private Car CAR; 
         
    // constructor use components, are acquired from the container 
    @Autowired
     public Boss (Car CAR) {
         the this .car = CAR; 
        the System.out .println ( "Boss ... there argument constructor" ); 
    } 
    
    public Car getCar () {
         return CAR; 
    } 

    public  void setCar(Car car) {
        this.car = car;
    }

    @Override
    public String toString() {
        return "Boss [car=" + car + "]";
    }
}

Aware injection underlying components and principles of the spring 

Custom components you want to use some of the components of the underlying Spring container (ApplicationContext, BeanFactory, xxx); custom components to achieve xxxAware; method when creating the object, it calls the interface specified injection-related components; Aware; some components injected into the bottom of the Spring Bean in the custom; 

Rules: xxxAware: function uses xxxProcessor

  ApplicationContextAware==》ApplicationContextAwareProcessor;

Profile ----- Spring we provide according to the current environment, the dynamic activation and switching of the set of components; 

Normal enterprise project will generally have a development environment, the test environment, the production environment; Data Source: (/ A) (/ B) (/ C);

@Profile : In the case of the specified components of the environment which can be registered to the container, do not specify any environment this component registered

Example: different environments using different data sources, data source without changing the code ----- use c3p0, mysql database

1、dbconfig.properties

db.user=root
db.password=123456
db.driverClass=com.mysql.jdbc.Driver

2、MainConfigOfProfile

package com.atguigu.config;


import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.util.StringValueResolver;

import com.atguigu.bean.Yellow;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
 * @Profile: In the case of the specified components of the environment which can be registered to the container, do not specify any environment this component can be registered 
 * 
 * 1), add the bean identified environment, this environment is only activated when they could registration into the container. The default is the default environment 
 * 2), written in the configuration class, only a specified environment, the entire configuration of all classes configured inside to begin to take effect 
 * 3), does not mark the environment identified in the bean, any environment is loaded the; 
 * / 
@PropertySource ( "CLASSPATH: /dbconfig.properties" ) 
@Configuration 
public  class MainConfigOfProfile the implements EmbeddedValueResolverAware { 
    
    @Value ( "db.User $ {}" )
     Private String User; 
    
    Private StringValueResolver valueResolver; 
    
    Private String driverClass; 
        
    // this bean is no environmental labeling, so any environment is loaded; If the environment, it will only be loaded in the corresponding environment    
    @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 the DataSource dataSourceProd (@Value ( "db.Password $ {}") String pwd) throws Exception { 
        ComboPooledDataSource the dataSource = new new ComboPooledDataSource (); 
        dataSource.setUser (User); 
        dataSource.setPassword (pwd); 
        the dataSource. setJdbcUrl ( "JDBC: MySQL: // localhost: 3306 / scw_0515" );         
        dataSource.setDriverClass (driverClass); 
        return the dataSource; 
    } 

    // this value resolver spring is provided, it can be resolved directly from the configuration file by StringValueResolver $ { } db.driverClass 
    @Override
     public  void setEmbeddedValueResolver(StringValueResolver resolver) {
        this.valueResolver = resolver;
        driverClass = valueResolver.resolveStringValue("${db.driverClass}");
    }

}

3, test category ----- IOCTest_Profile

package com.atguigu.test;

import javax.sql.DataSource;

import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.atguigu.bean.Boss;
import com.atguigu.bean.Car;
import com.atguigu.bean.Color;
import com.atguigu.bean.Red;
import com.atguigu.bean.Yellow;
import com.atguigu.config.MainConfigOfProfile;
import com.atguigu.config.MainConifgOfAutowired;
import com.atguigu.dao.BookDao;
import com.atguigu.service.BookService;

public class{IOCTest_Profile 
    
    // . 1, the command line using the dynamic parameter: loading -Dspring.profiles.active = test position in the virtual machine parameters
     // 2, the code of activating a mode environment; 
    @Test
     public  void Test01 () { 
        AnnotationConfigApplicationContext applicationContext = new new AnnotationConfigApplicationContext ();
         // . 1, create a applicationContext
         // 2, set the environment to be activated is 
        applicationContext.getEnvironment () setActiveProfiles ( "dev." );
         // . 3, the main configuration register class 
        applicationContext.register (MainConfigOfProfile. class );
         // 4, start refresh container 
        applicationContext.refresh (); 
    } 

}

Note:

1, @Profile greater than the class method @Profile; ----- if the current environment is "dev", and the configuration class @Profile to test, then the void corresponding to the entire class.

2, How to change the operating environment? ----- a, directly -D spring.profiles.active = dev b, to set by applicaitonContext

Guess you like

Origin www.cnblogs.com/alimayun/p/11105329.html