Spring Core Module

Source: Internet
Author: User

Spring Core Module

 

The Core module Implements control inversion and dependency injection, Bean configuration, and loading. The Core module includes Beans, BeanFactory, BeanDefinitions, and ApplicationContext.

BeanFactory

BeanFactory is a container that instantiates, configures, and manages many beans.

Beanfactory does not need to be instantiated in the Web program. BeanFactory is automatically instantiated when the Web program is loaded and the Beans of the worker are loaded, set each Bean to Servlet, Struts Action, or Hibernate resource.

In a Java Desktop program, you need to obtain beans from BeanFactory. Therefore, you need to instantiate BeanFactory. For example, load the configuration file under ClassPath:

 

ClassPathResource  res = new ClassPathResource("applicationContext.xml");XmlBeanFactory  factory = new XmlBeanFactory  (res);Iservice service= factory.getBean("service");……factory.destroySingletons();

 

Or use a file stream to load configuration files in any location

 

InputStream  in = new FileInputStream("C:\\ApplicationContext.xml");XmlBeanFactory  factory = new XmlBeanFactory  (in);

You can also use ClassPathXmlApplicationContext to load multiple configuration files (transmitted as strings)

 

 

ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext (new String [] {"applicationContext. xml "," applicationContext-part2.xml "}); www. bkjia. comBeanFactory factory = (BeanFactory) appContext; // ApplicationContext inherits from BeanFactory Interface

 

Configure Bean

Factory Model

If a bean cannot be directly instantiated through new, but is created through a method of the factory class The class attribute of is configured as the factory class (or the factory-bean attribute is configured as the factory class object)

 

  
   
   
  

 

Constructor

If the Bean constructor has parameters, you must specify the constructor parameters.

 

        
   
    
         
   
    
         
   
    
     1
    
   
  

Parameters are in the same order as the constructor parameters.

 

 

Single Mode

Bean can be defined as single-State mode. In non-single-State mode, a new object is generated each time the Bean is requested.

Such as data sources are generally configured in single-State mode.

 

  

 

Property

The destroy-method attribute is used to disable the method. If the method is configured, this method is called when the Java object is discarded. For some data sources and SessionFactory objects, you must use destroy-method to disable the method.

 

  

Equivalent

 

 

        
   
    pValue
   
  

 

Note:

 

        
   
  

 

The password is set to "" instead of null. If you want to set it to null, it should be

 

        
   
  

 

Attribute

Beans in the Spring configuration file can be referenced from each other. Use tags with Bean id attributes

You can also useInternal Configuration

 

  
        
                
          
    
   
  

Equivalent to internal configuration

 

 

        
   
  

 

Besides You can also use local and parent for bean properties. They have the same role as bean properties. However, local can only use beans in this configuration file, while parent can only use beans in the parent configuration file.

 

Attribute

 

        
                
    
     
String, Integer, Double, and other data types
                 
          
    
   
  

 

Attribute

 

        
                
    
     
String, Integer, Double, and other data types
                 
          
    
   
  

 

Attribute

 

  
                
                        
     
      
String, Integer, Double, and other data types
                  
                 
                        
                  
     
    
  

 

Attribute

 

        
                
    
     http://localhost:8080/clf
                 
    
     clf
          
    
   
  

 

And Attribute

 

  
   ……
  


 

Spring will call the close method when logging out of these resources.

 

Some objects need to execute some initialization code after instantiation, but these Code cannot be written into the constructor. At this time, you can write the initialization code into a method and use Specify this method

 

  

 

Depends-on Attributes

Spring will instantiate the Bean in the Bean sequence in the configuration file by default, but sometimes the B object needs to be instantiated before object A is instantiated. In this case, you can use the depends-on attribute to force object B to be instantiated first.

 

  
  

 

And Difference

And The role is the same. Java objects are configured. The difference is that, Only the bean and local attributes are available, and the parent attributes are not available.

When Spring loads the XML configuration file, it checks The configured Bean is not there, while It will only be checked during the first call. In other words, if the Bean does not exist, When the program is started, an error is thrown. Only an error is thrown during running.

 

You can use the autowire attribute of Bean to set Automatic Assembly rules. Autowire does not need to be used again Explicitly set the attributes and dependencies of the Bean. Spring automatically searches for qualified Attributes Based on reflection and sets them to the Bean.

The autowire property defines not the name of the property to be automatically assembled, but the automatic assembly rules. Once configured, all attributes will follow the rules defined by autowire.

 

No: automatic assembly is disabled. The default value of Autowire.

ByName: searches for and injects the objects on which the JavaBean depends using the attribute name. For example, if the Computer class has a printer attribute and Its autowire attribute is set to byName, the Spring IoC container will find the bean whose id/name attribute is printer in the configuration file, then use the Setter method to inject it.

ByType: searches for and injects the objects on which the JavaBean depends based on the attribute type. For example, if the Class Computer has a printer attribute whose type is Printer, after specifying its autowire attribute as byType, the Spring IoC container will find the bean whose Class attribute is Printer, use the Setter Method for injection.

Constructor: similar to byType, it also finds dependent objects by type. The difference with byType is that it uses constructor instead of Setter injection.

Autodetect: automatically selects the injection mode between byType and constructor.

Default: the upper-level label The default-autowire attribute of is determined.

 

Dependency-check

Sometimes the attribute configuration of some beans is incorrect. This error will not occur when the program starts, and will remain hidden until Spring calls the Bean.

The dependency check can check whether the attribute is set. If the dependency check is configured, configuration verification is performed when the program is started to detect errors in a timely manner.

However, it should be noted that the dependency check is very rigid. For example, if it is set to an object, all Java object attributes will be checked. If one attribute is not set, an exception will be thrown.

 

No or default: no check is performed. The default value is

Simple: Only checks basic types and set attributes.

Object: only check Java object attributes

All: Check all attributes

Advanced Bean features

BeanNameAwareInterface helps Bean know its id in the configuration file

 

Import org. springframework. beans. factory. beanNameAware; public class BeanNameTest implements BeanNameAware {private String beanName; // Spring will call this method public void setBeanName (String beanName) {this. beanName = beanName ;}}

 

BeanFactoryAwareInterface helps Bean to know which BeanFactory has instantiated itself

 

public interface  BeanFactoryAware{      void setBeanFactoryAware(BeanFactory beanFactory) throws BeanException;}

 

Same as BeanNameAware

There are also common methods

Boolean containsBean (String) determines whether the Bean with the specified name exists

Object getBean (String) returns the specified name. If this Bean is not present, an exception is thrown.

Object getBean (String, Class) returns the Bean with the specified name and converts it to the specified Class Object.

Boolean isSingleton (String) determines whether the Bean with the specified name is configured in single-State mode.

String [] getAliases (String) returns the alias of the Bean with the specified name

 

InitializingBeanThe interface calls the initialization method after Bean instantiation and after all attributes are set. However, using this interface will be coupled with the Spring code, so it is not recommended that you use it. The init-method Configuration is recommended for Spring.

 

Public interface InitializingBean {public void afterPropertiesSet (); // call this method during initialization}

 

 

DisposableBeanThe interface calls the destroy method when the Bean object is discarded.

 

Public interface DisposableBean {public void destroy (); // call this method during destruction}

 

Property overlay

For some parameters, the more practical and simpler method is to use properties configuration, instead of configuring in the Spring configuration file.

PropertyplaceholderpolicerSome parameters configured in XML can be configured in the properties file.

 

        
         
          
           
      
     
    
   
   
        
   
  

 

Jdbc. properties

 

jdbc.driverClassName= com.mysql.jdbc.Driverjdbc.url =jdbc:mysql://localhost:3306/clf?characterEncoding=UTF-8jdbc.username =clfjdbc.password =admin


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.