Spring simple example

References: https://how2j.cn/k/spring/spring-ioc-di/87.html , https://www.w3cschool.cn/wkspring/dgte1ica.html

1. Open your IDE and create basic Java Project

 

2. Download and import the Spring jar package

Download: https: //how2j.cn/frontdownload bean.id = 1484?

Once you have downloaded, extract them to the project's lib folder inside the folder if it does not create a new one. After decompression, method of introducing each of these jar coated with the IDE

 

3. Create two classes

Code comments as follows:

public  class the Category {
     // attributes 
    Private String name;
     // Set the attribute method 
    public  void the setName (String name) {
         the this .name = name; 
    } 
    // Get the attribute method 
    public  void getName () { 
        the System.out. the println (name); 
    } 
}
public  class TestSpring {
     public  static  void main (String [] args) {
         // applicationContext.xml own configuration file is created 
        ApplicationContext context = new new ClassPathXmlApplicationContext ( "applicationContext.xml" );
         // c is the id back profile 
        Category category = (the Category) context.getBean ( "C" ); 
        category.getName (); 
    } 
}

Taken w3, need to be aware of two things:

  • The first point is that we use the framework API  ClassPathXmlApplicationContext ()  to create the context of the application. This API is loaded beans profile based API and final offer, which handles the creation and beans initialize all the objects that are mentioned in the configuration file.

  • The second point is the context of already created  getBean ()  to obtain the desired bean method. This method returns the bean ID can be converted to a common final object of the actual object. Once you have the object, you can use this object to call any class method.

4. New Profile

Profile suffix xml, needs its own new. Configuration file as follows:

<? XML Version = "1.0" encoding = "UTF-. 8" ?> 
< Beans xmlns = "http://www.springframework.org/schema/beans" 
       xmlns: the xsi = "http://www.w3.org / 2001 / the XMLSchema-instance " 
       the xsi: the schemaLocation =" http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd " > 

<! -     ID own name, class attributes that need to inject class -> 
    < the bean ID = "C" class = "the category" > 
<-!         name is the name of the attribute, value is injected into the value of the property -> 
        <property name="name" value="Hello Word"/>
    </bean>
</beans>

 

5. Review the operating results

Finally, our operating results is injected

Hello Word

Guess you like

Origin www.cnblogs.com/lbhym/p/11892428.html