Spring (1)-functions, IOC container details, matching environment, Spring experiment, springioc

Source: Internet
Author: User

Spring (1)-functions, IOC container details, matching environment, Spring experiment, springioc
1. Role of Spring:
1. the ecosystem is huge. All players! Springmvc is a sub-module. jdbcTemplate can directly operate databases !]
2. Bond other components together
For example, connect SpringMVC and Mybaits.
3. including IOC container and AOP [Aspect-Oriented Programming]
Spring's IOC mechanism (control inversion and dependency injection) is used here.
Spring IOC (control inversion and dependency injection)
Control inversion [IOC]: it refers to the (dependency) Relationship between container control programs. In non-traditional implementations, it is directly controlled by program code.
Control reversal is an idea. Its specific implementation is dependency injection! Dependency Injection [DI: Dependency Injection]: dependencies between components are determined by the runtime of the container, and the container dynamically injects a Dependency into the component. For example, in the controller layer, to call the service layer method, there is no need for a new object. In the form of annotations, the object is put into the container for calling, which uses the dependency injection 2. IOC container details
1. Create an object using the IOC container
2. when creating an object using the IOC container, assign a value to the object attribute 3. during object creation, automatic assembly between component objects is realized. build the development environment required by the Spring IOC container
1. Import the jar package required by the IOC container
Spring-beans-4.0.0.RELEASE.jar
Spring-context-4.0.0.RELEASE.jar spring-core-4.0.0.RELEASE.jar spring-expression-4.0.0.RELEASE.jar commons-logging-1.1.3.jar 2. Create Spring Configuration File [Spring bean Configuration File]Experiment 1: Create an object through the IOC container and assign a value to the attribute<! -- The full Class Name of the object needs to be created by the IOC container --> <property> is injected through the set method, so the object class must have the set Method

<! -- Class specifies the full class Name of the class object. It is a unique identifier to create an object id on the server, only one bean object whose id is book can appear in IOC --> <bean id = "book" class = "com. neuedu. spring. bean. book "> <property name =" bookName "value =" JAVA "> </property> <property name =" author "value =" you "> </property> <property name = "price" value = "123.123"> </property> </bean>

 

Public class TestIOC {@ Test public void test () {// 1. obtain the IOC container's own ApplicationContext ioc = new ClassPathXmlApplicationContext ("applicationContext. xml "); // 2. obtain the bean Object bean = IOC from the ioc container. getBean ("book"); System. out. println (bean );}}

 

Note:
① When an IOC container object is created, the bean configured in the configuration file is created first.
② By default, only one bean object is created for a single instance.
③ If the scope attribute of bean is set to prototype, the bean object to be created is multi-instance. When the bean is obtained, a new
④. Get the object from the IOC container
① Obtain according to bean id ② obtain according to bean type: requires the bean of the specified type in the container to be the unique post-processor of bean:
1. It refers to a special object that performs operations before and after the bean initialization method.
2. Custom postprocessors:
1) interface: org. springframework. beans. factory. config. BeanPostProcessor.
2) make the appropriate configuration! Experiment 2: Obtain the bean instance from the IOC container Based on the bean type 
Public class TestIOC {@ Test public void test () {// 1. obtain the IOC container's own ApplicationContext ioc = new ClassPathXmlApplicationContext ("applicationContext. xml "); // 2. obtain the bean object Book bean = IOC from the ioc container. getBean (Book. class); System. out. println (bean. getBookName () + "---" + bean. getAuthor () + "---" + bean. getPrice ());}}

Note that there must be no parameter constructor when creating an object class. If there is no parameter, there will be a non-parameter constructor by default. However, if there is a parameter constructor, the object cannot be built and the bean instance cannot be obtained.

 

Experiment 3: constructors that assign values to bean attributes, specify the parameter location through index attributes, and distinguish between overloaded constructors by Different TypesAssign a value to the constructor through <constructor-arg> and sort the attribute by index, so that the order of the attribute and the constructor with parameters is always the same. The index starts from 0, type specifies the type of the value you entered, and then the value is paid to the corresponding object class attribute. For example, "22.22" will be paid to the double modified attribute, rather than other attributes.
<bean id="book01" class="com.neuedu.spring.bean.Book">     <constructor-arg value="you" index="1"></constructor-arg>     <constructor-arg value="C++" index="0"></constructor-arg>     <constructor-arg value="22.22" index="2" type="double"></constructor-arg></bean>

 

 

  Experiment 4: assign values to bean cascade attributesCreate three entity classes. The first class contains the second class, the second class contains the third class, and the third class has a username attribute for the get, set, and toString methods respectively.
public class StudentController {      private StudentService studentService;      public StudentService getStudentService() {            return studentService;      }      public void setStudentService(StudentService studentService) {            this.studentService = studentService;      }      @Override      public String toString() {            return "StudentController [studentService=" + studentService + "]";      }}

 

public class StudentService {      private StudentDao studentDao;      public StudentDao getStudentDao() {            return studentDao;      }      public void setStudentDao(StudentDao studentDao) {            this.studentDao = studentDao;      }      @Override      public String toString() {            return "StudentService [studentDao=" + studentDao + "]";      }}

 

public class StudentDao {      private String username;      public String getUsername() {            return username;      }      public void setUsername(String username) {            this.username = username;      }      @Override      public String toString() {            return "StudentDao [username=" + username + "]";      }}
Value can only assign values to strings. ref points to the object and matches the Object id. The final page calls studentController.
<! -- Assign a value to the cascading attribute of bean --> <bean id = "studentDao" class = "com. neuedu. spring. bean. studentDao "> </bean> <bean id =" studentService "class =" com. neuedu. spring. bean. studentService "> </bean> <bean id =" studentController "class =" com. neuedu. spring. bean. studentController "> <property name =" studentService "ref =" studentService "> </property> <property name =" studentService. studentDao "ref =" studentDao "> </property> <property name =" studentService. studentDao. username "value =" zhangsan "> </property> </bean>

 

Public class TestIOC {@ Test public void test () {// 1. obtain the IOC container's own ApplicationContext ioc = new ClassPathXmlApplicationContext ("applicationContext. xml "); // 2. obtain the bean Object bean = IOC from the ioc container. getBean ("studentController"); System. out. println (bean );}}

 

 

  Experiment 5: assign values to bean using p namespaceSelect the p tag in the namespace in the spring. xml file.
<! -- Assign values to bean through p namespace --> <bean id = "student" class = "com. neuedu. spring. bean. student "p: name =" zhangsan "p: gender =" 1 "p: address =" China "> </bean>

 

  Experiment 6: test the bean scope. Create single-instance and multi-instance beans respectively.Input one sentence in the no-argument constructor of the two entity classes to determine whether the object is created several times through the scope control singleton or multiple examples: singleton is singleton; prototype is a multi-instance singleton. It is created when the IOC container is created. Multiple instances are created every time the bean object is obtained.
<! -- Test the bean scope and create a single-instance and multi-instance bean respectively --> <bean id = "book2" scope = "singleton" class = "com. neuedu. spring. bean. book "> </bean> <bean id =" student2 "scope =" prototype "class =" com. neuedu. spring. bean. student "> </bean>

Show one book and three student

 
Public class TestIOC {// 1. obtain the IOC container's private ApplicationContext ioc = new ClassPathXmlApplicationContext ("applicationContext. xml "); @ Test public void test () {ioc. getBean ("book"); ioc. getBean ("book"); ioc. getBean ("book"); ioc. getBean ("student"); ioc. getBean ("student"); ioc. getBean ("student ");}}

 

  Experiment 7: Create a bean with a lifecycle MethodInput one sentence in the no-argument constructor of the two object classes to determine whether the object is created.
<bean id="book" class="com.neuedu.spring.bean.Book"></bean><bean id="student" class="com.neuedu.spring.bean.Student"></bean>
Test () does not write anything. After running, it finds that both objects are created. This means that when the ioc container is created, the object is created.
public class TestIOC {      private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");      @Test      public void test() {      }}

 

Experiment 8: Create a bean with a lifecycle MethodCreate two methods in the object class: init () and destroy () enter "init method execution" and "destroy method execution", and add init-method and destroy-method to the bean to correspond to the init method and destroy method respectively.
<bean id="teacher" class="com.neuedu.spring.bean.Teacher" init-method="teacherinit" destroy-method="destroy"></bean>

However, the destroy method cannot be called. The destroy method is called through the close method of the subclass of ApplicationContext.

public class TestIOC {      private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");      @Test      public void test() {            ConfigurableApplicationContext cac = (ConfigurableApplicationContext) ioc;            ioc.getBean("teacher");            cac.close();      }}

 

 

  Experiment 9: depends-on = "order" dependencies between beans are created first.If no depends-on is available, the object will be created in the bean order, but after the object is created, it will be created first. In this example, book depends on student, so student will be created first.
<bean id="book" class="com.neuedu.spring.bean.Book" depends-on="student"></bean><bean id="student" class="com.neuedu.spring.bean.Student" ></bean><bean id="teacher" class="com.neuedu.spring.bean.Teacher" init-method="teacherinit" destroy-method="destroy"></bean>

 

  Experiment 10: Reuse bean configuration information through inheritanceUse parent to inherit from book1 the bookName of the book and the other two of author are modified. Output book1 will output the Book [bookName = JAVA, author = you, price = 34.23, isbn = house]
<bean id="book" class="com.neuedu.spring.bean.Book">     <property name="bookName" value="JAVA"></property>     <property name="author" value="you"></property>     <property name="price" value="43.43"></property>     <property name="isbn" value="home"></property></bean><bean id="book1" class="com.neuedu.spring.bean.Book" parent="book">     <property name="price" value="34.23"></property>     <property name="isbn" value="house"></property></bean>

 

 

  Experiment 11: Create a template bean through abstract attributesAbstract The book object so that the book object cannot be called, but the sub-object book1 can be called.
<bean id="book" class="com.neuedu.spring.bean.Book" abstract="true">     <property name="bookName" value="JAVA"></property>     <property name="author" value="you"></property>     <property name="price" value="43.43"></property>     <property name="isbn" value="home"></property></bean><bean id="book1" parent="book">      <property name="price" value="43.43"></property>      <property name="isbn" value="home"></property></bean>

 

  Experiment 12: test the use of null valuesIf the book attribute is missing author, null is displayed.
<bean id="book" class="com.neuedu.spring.bean.Book">     <property name="bookName" value="java"></property>     <property name="price" value="33.5"></property>     <property name="isbn" value="house"></property></bean>

You can also write <null/> to <property>.

<bean id="book" class="com.neuedu.spring.bean.Book">     <property name="bookName" value="java"></property>     <property name="author">            <null/>     </property>     <property name="price" value="33.5"></property>     <property name="isbn" value="house"></property></bean>
The preceding values are of the String type. If the values are of the int or double type, <null/> <value = "0"> cannot be used. Therefore, the 0/0. 0 packaging class is displayed as null. Experiment 13: reference other beansCreate a new BookShop that contains the book attributes. Call bookShop through the ref connection.
<Bean id = "book" class = "com. neuedu. spring. bean. book "> <property name =" bookName "value =" java "> </property> <property name =" isbn "value =" house "> </property> </bean> <bean id = "bookShop" class = "com. neuedu. spring. bean. bookShop "> <property name =" address "value =" Hebei "> </property> <property name =" book "ref =" book "> </property> </bean>

 

 

  Tutorial 14: Reference internal beansDeclare a bean in the bean
<Bean id = "bookShop" class = "com. neuedu. spring. bean. bookShop "> <property name =" address "value =" Hebei "> </property> <property name =" book "> <bean class =" com. neuedu. spring. bean. book "> <property name =" bookName "value =" java "> </property> <property name =" author "value =" you "> </property> <property name = "price" value = "43.32"> </property> <property name = "isbn" value = "house"> </property> </bean> </property> </bean>

 

  Tutorial 15: Use List-type set attributesAdd the bookList attribute to the BookShop class, and add the set/get method bookList to the ref: book1, book2, book3, and book4
<bean id="book1" class="com.neuedu.spring.bean.Book">     <property name="bookName" value="java"></property></bean><bean id="book2" class="com.neuedu.spring.bean.Book">      <property name="author" value="you"></property></bean><bean id="book3" class="com.neuedu.spring.bean.Book">      <property name="price" value="43.43"></property></bean><bean id="book4" class="com.neuedu.spring.bean.Book">      <property name="isbn" value="home"></property></bean><bean id="bookShop" class="com.neuedu.spring.bean.BookShop">      <property name="bookList">           <list>                 <ref bean="book1"/>                 <ref bean="book2"/>                 <ref bean="book3"/>                 <ref bean="book4"/>            </list>      </property></bean>

 

public class TestIOC {      private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");      @Test      public void test() {            BookShop bean = ioc.getBean(BookShop.class);            List<Book> bookList = bean.getBookList();            for(Book book : bookList){                  System.out.println(book);            }      }}

 

 

  Tutorial 16: using Map-type set attributesAdd the Map attribute to the BookShop class and add the set/get method <map> with <entry>. A key-value pair is a <entry>
<bean id="bookShop" class="com.neuedu.spring.bean.BookShop">     <property name="bookMap">           <map>               <entry>                     <key>                          <value>book1</value>                     </key>                     <ref bean="book1"/>                </entry>                <entry>                      <key>                           <value>book2</value>                       </key>                       <ref bean="book2"/>                 </entry>                 <entry>                        <key>                            <value>book3</value>                        </key>                        <ref bean="book3"/>                  </entry>                  <entry>                         <key>                             <value>book4</value>                         </key>                         <ref bean="book4"/>                  </entry>            </map>      </property></bean>

Traverse map sets with. entry

public class TestIOC {      private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");      @Test      public void test() {            BookShop bean = ioc.getBean(BookShop.class);            Map<String, Book> bookMap = bean.getBookMap();            Set<Entry<String,Book>> entrySet = bookMap.entrySet();            for (Entry<String, Book> entry : entrySet) {                  System.out.println(entry.getKey()+"==="+entry.getValue());            }      }}

 

 

  Experiment 17: assign values to Properties using the prop sub-elementAdd the Properties attribute to the BookShop class and add the set/get method.
<bean id="bookShop" class="com.neuedu.spring.bean.BookShop">      <property name="p">            <props>                 <prop key="book1">value1</prop>                 <prop key="book2">value2</prop>                 <prop key="book3">value3</prop>                 <prop key="book4">value4</prop>            </props>      </property></bean>

 

public class TestIOC {      private ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");      @Test      public void test() {            BookShop bean = ioc.getBean(BookShop.class);            java.util.Properties p = bean.getP();            System.out.println(p.get("book1"));            System.out.println(p.get("book2"));            System.out.println(p.get("book3"));            System.out.println(p.get("book4"));      }}

 

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.