Spring explain (a)

1, how to understand the Spring Framework

Briefly, Spring is a lightweight inversion of control (IoC) and the facing section (AOP) of the container frame .

Because I used to write code, when using class objects, often need to be instantiated to create a (new up) many objects, sometimes only need to instantiate the object once (regardless of whether the object is a service or dao), let go of the object do the right thing.

The Spring Framework is the management of these objects, so the Spring container assembly management of these objects, and then taken out to use the program ape needs, make creating and using objects easier.

[Bean is actually a good new objects]

2, the benefits of using Spring

  • Convenient decoupling, simplify development

    Spring is a large factory, responsible for generating Bean, can be created and maintained by the Spring dependencies to manage all objects.

  • AOP programming support

    Spring provides aspect-oriented programming, you can easily implement a program permission to intercept, operation monitoring and other functions.

  • Support for declarative transactions

    Only you need to complete the configuration management of the affairs, without the need for manual programming.

  • To facilitate the testing program

    Spring for Junit4 support, you can easily comment Spring test program.

  • Easy integration of a variety of excellent framework

    Spring does not exclude a variety of excellent open source framework, which provides a variety of excellent internal framework: support (such as Struts, Hibernate, MyBatis, Quartz, etc.).

  • The difficulty of reducing the use of JavaEE API

    JavaEE development of some difficult to use API (JDBC, JavaMail, remote tune with webservice, etc.), provides packaging so that these API application difficulty greatly reduced.

3, said so much, is a mule is a horse, pull out yo (case presentations)

  • Create the interface and implementation class

    public interface UserService {
        void add();
    }
    
    =============================================================================
    public class UserServiceImpl implements UserService {
        @Override
        public void add() {
            System.out.println("创建用户....");
        }
    }
  • Spring does not use the calling object method

    public class ServiceTest {
        public static void main(String[] args) {
            UserService userService=new UserServiceImpl();
            userService.add();
        }
    }

    Print Console log results: Create a user ....

  • Use Spring managed objects

    首先需要创建 bean.xml 文件
    <?xml version="1.0" encoding="UTF-8"?>
        <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
                <!-- 配置一个bean 【对象】-->
                <bean id="userService" class="com.example.demo.service.impl.UserServiceImpl"/>
    </beans>
     public class ServiceTest {
         public static void main(String[] args) {
    
             //1.加载beans.xml 这个spring的配置文件,内部就会创建对象
             ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    
             //2.从spring容器获取 userSerivce对象
             UserService userSerivce1 = (UserService) context.getBean("userService");
             userSerivce1.add();
    
             UserService userSerivce2 = (UserService) context.getBean("userService");
             userSerivce2.add();
    
             System.out.println(userSerivce1);
             System.out.println(userSerivce2);
         }
     }

Console logs print the results as follows:

Create a user ....

Create a user ....

com.example.demo.service.impl.UserServiceImpl@3b088d51
com.example.demo.service.impl.UserServiceImpl@3b088d51

Spring can be seen in the boot loader configuration file bean.xml time, this object will be created in the container, when the need to use direct access can be.

Compared to the previous every time new (new process frequently subject to significant program cost) of an object. This object is created only once after to the Spring container, the address is the same as the value of print.

2, in Spring IOC and DI explain

  • IoC inversion control

    It was originally created UserService control objects in your program manually, handed over management of the Spring framework. It simply is to create objects UserService control is reversed to the Spring framework.

  • DI Dependency Injection

    When the Spring Framework Bean is responsible for creating objects, dynamic objects will depend injected into the Bean components.

  • Dependency injection (DI) case presentations

    public class UserServiceImpl implements UserService {
    
        private String name;
    
      // 可以注释掉 getName 方法
        public String getName() {return name;}
    
        // setName 方法不可以注释掉
        public void setName(String name) {this.name = name;}
    
        @Override
        public void add() {
            System.out.println("创建用户...." + name);
        }
    }
     <?xml version="1.0" encoding="UTF-8"?>
            <beans xmlns="http://www.springframework.org/schema/beans"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
                <!-- 配置一个bean 【对象】-->
                <bean id="userService" class="com.example.demo.service.impl.UserServiceImpl">
                    <!-- 依赖注入数据,调用属性的set方法 -->
                    <property name="name" value="zhangsan"></property>
                </bean>
            </beans>

    Main method of operation of the original console logs print the results as follows:

    Create a user .... zhangsan

    Create a user .... zhangsan

    com.example.demo.service.impl.UserServiceImpl@7a187f14
    com.example.demo.service.impl.UserServiceImpl@7a187f14

  • Emphasis

    If UserServiceImpl commented getName, the program does not go wrong. If commented setName method, an error is reported as follows, for reasons given, and the explanation see a.

    Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService' defined in class path resource [beans.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'name' of bean class [com.example.demo.service.impl.UserServiceImpl]: Bean property 'name' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1718)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1433)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
      at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845)
      at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
      at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:144)
      at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:85)
      at com.example.demo.testservice.ServiceTest.main(ServiceTest.java:16)
    Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'name' of bean class [com.example.demo.service.impl.UserServiceImpl]: Bean property 'name' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
      at org.springframework.beans.BeanWrapperImpl.createNotWritablePropertyException(BeanWrapperImpl.java:243)
      at org.springframework.beans.AbstractNestablePropertyAccessor.processLocalProperty(AbstractNestablePropertyAccessor.java:426)
      at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:278)
      at org.springframework.beans.AbstractNestablePropertyAccessor.setPropertyValue(AbstractNestablePropertyAccessor.java:266)
      at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:97)
      at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:77)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1714)
      ... 13 more

Guess you like

Origin www.cnblogs.com/miantiao312/p/11790088.html