Spring Experience 1--spring Introductory introduction @bean The first spring project Helloword

Source: Internet
Author: User
Tags aop

1. Start Spring Tour

Spring is an open source control reversal (inversion of controls, IOC) and a container framework for aspect-oriented (AOP). Its main aim is to simplify enterprise development.

The Help document path, under the existing path of the Springjar package:

spring-framework-3.2.2.release-dist\spring-framework-3.2.2.release\docs\spring-framework-reference\html Web Help Document

Spring-framework-3.2.2.release-dist\spring-framework-3.2.2.release\docs\spring-framework-reference\pdf PDF document

IOC Control reversal

public class Personservicebean {

Private Persondao Persondao = new Persondaobean ();

public void Save (person person) {

Persondao.save (person);

}

}

Persondaobean is created and maintained within the application . The so-called control reversal is that the application itself is not responsible for the creation and maintenance of dependent objects, and the creation and maintenance of dependent objects are handled by the external container. Thus the control is transferred from the application to the external container, and the transfer of control is the so-called reversal.

L -Dependency Injection (Dependency injection)

When we give the dependent object to the external container to create it, the Personservicebean class can be changed as follows:

public class Personservicebean {

Private Persondao Persondao;

By using the constructor parameters, the container injects the created dependent object into the Personservicebean, and of course it can be injected with the setter method.

Public Personservicebean (Persondao Persondao) {

This.persondao=persondao;

}

public void Save (person person) {

Persondao.save (person);

}

}

Dependency Injection means that, at runtime, a dependent object is dynamically injected into an assembly by an external container.

2. Why to use spring

1 to reduce the coupling between the components, the software to achieve the decoupling between the layers.

2 You can use a number of services provided by the container, such as transaction management services, messaging services , and so on. When we use containers to manage transactions, developers no longer need to manually control transactions. Nor does it need to handle complex transactional propagation.

3 The container provides a single case mode support, and developers no longer need to write the implementation code themselves.

The container provides AOP technology, it is easy to implement such functions as permission interception, runtime monitoring and so on.

4 The container provides a number of auxiliary classes, using these classes can accelerate the development of applications, such as: JdbcTemplate, Hibernatetemplate.

Spring provides integrated support for the mainstream application framework, such as integrated hibernate, JPA, struts, and so on, which makes it easier to develop applications.

3. Additional Considerations for Spring

L Spring's profile templates

<?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-2.5.xsd ">

.....

</beans>

The profile template is available from the Spring Reference manual (Spring help store Path/spring-framework-3.2.2.release-dist/spring-framework-3.2.2.release/docs/ Spring-framework-reference/html/beans.html in the fifth chapter of Beans-factory-metadata) or spring's example. The name of the configuration file can be arbitrary, the file can be stored in any directory, but given the generality, generally placed in the classpath.

when writing a spring configuration file, no Help information will appear

Because spring's schema file is located on a network, if the machine cannot connect to the network, the message cannot be prompted when the configuration information is written , and there are two ways to resolve it:

1 Let the machine surf the web, eclipse will automatically download the schema file from the network and cache it on the hard disk.

2 Add the schema file manually by adding the following methods:

Windwos->preferences->myeclipse->files and editors->xml->xmlcatalog; point "add", select the URI in the key type in the window that appears. Select "File system" in location, then choose Spring-beans-2.5.xsd in the Dist/resources directory of Spring extract directory, return to the setting window, don't rush to close the window, the key in the window should be Type changed to Schema Location,key to Http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

4. Assembling beans (first lecture)

one, to accommodate your bean

Bean Factory : The simplest container that provides the foundation for dependency injection support. Create various types of beans.

Application Context : Built on the bean factory basis, providing system architecture services.

A 1 Bean Factory Introduction

Factory design mode, creating distribution of various beans. Configure the writing relationships between them to participate in the bean lifecycle. The Bean factory simply loads the bean's definition information and instantiates it when it is used.

A 2 Using the application context

Applicationcotext,spring a more advanced container. Strong function:

1. Provides parsing tools for text information, including support for internationalization.

2. Provides a common method for loading file resources, such as pictures.

3. You can send an event to a bean registered as a listener.

In rare cases, use beanfactory, such as in mobile devices.

three types of implementations that are often used :

1). Classpathxmlapplicationcontext: Loading from the classpath.

2). Filesystemxmlapplicationcontext: Loading from File system.

3). Xmlwebapplicationcontext: Loading from the web system.

ApplicationContext context = new Filesystemxmlapplicationcontext ("C:\foo.xml");

ApplicationContext context = new Classpathxmlapplicationcontext ("Foo.xml");

In addition to the additional functionality provided by the application context, another important difference between the application context and the Bean factory is about how the single instance bean is loaded. The Bean factory delays loading all beans until the Getbean () method is invoked. The application context preload all the single instance beans after startup. This ensures that the application does not need to wait for them to be created.

4. Case: First Spring Java project

The change case only lists the important configuration file and the test class, the other class does not have the nutrition to repeat again; The following are a few of the configuration files and key classes that need to be noted and the corresponding explanatory notes.

Spring.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.springframewor K.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> <import Resou  Rce= "Spring-dao.xml"/> <import resource= "Spring-service.xml"/> </beans> spring-dao.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 htt P://www.springframework.org/schema/beans/spring-beans.xsd "> <!--Spring Container is responsible for creating, managing, maintaining beans and being able to rely on injection into the appropriate components--&

   Gt

      <bean id= "Hellodaoimpl" class= "Www.csdn.spring.dao.impl.HelloDaoImpl" scope= "prototype" ></bean> <!--referenced by Spring-service.xmlChange the configuration file, so in the former added lazy-init= "false", here can not write will also work; the Lazy-init attribute means: whether to delay loading is to instantiate the corresponding container object as soon as the spring container is created, that is, to execute the constructor for the object being modified, Instead of loading lazy-init= "false" at the time of use, the default value is defaults, but Default=false--> </beans> spring-service.xml &L t;? XML version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans"

           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 id=" helloserviceimpl "class=" www. Csdn.spring.service.impl.HelloServiceImpl "scope=" singleton "lazy-init= false" > <property "name=" re

 

f= "Hellodaoimpl"/> </bean> </beans> demotest class package www.csdn.spring.test;

Import Org.junit.Test;

Import Org.springframework.context.ApplicationContext;

 

Import Org.springframework.context.support.ClassPathXmlApplicationContext; Import www.Csdn.spring.dao.HelloDao;

Import Www.csdn.spring.dao.impl.HelloDaoImpl;

Import Www.csdn.spring.service.HelloService;

 

Import Www.csdn.spring.service.impl.HelloServiceImpl; public class Demotest {@Test the public void Testhello () {//container to create an instantiated container; Read classes

              

              

              The path below the file parameter dynamic parameters, single parameters, arrays, etc. applicationcontext context = new Classpathxmlapplicationcontext ("Spring.xml"); Use DAO and Daoimpl to write a: use DAO to get beans; here Getbean the corresponding spring in parentheses.

              The id attribute name of the bean label in the configuration file Hellodao HelloDao1 = (Hellodao) context.getbean ("Hellodaoimpl"); It can also be written like this: but generally not, because Java is all interface-oriented programming, so declare the type of interface as far as possible rather than implementing the type Hellodaoimpl HELLODAOIMPL1 = (Hellodaoimpl) con

              

              Text.getbean ("Hellodaoimpl"); Write two: Also use DAO to get beans, the official website writes, the comparison standard writing Hellodao HelloDao2 = (Hellodao) context.getbean ("Hellodaoimpl", Hellodaoim

              Pl.class); You can also write this: but generallyNot so, because Java is all interface-oriented programming, so declare the type of the interface as much as possible instead of implementing the type Hellodaoimpl HELLODAOIMPL2 = (Hellodaoimpl) Context.getbean (

              

              

              "Hellodaoimpl");  Use service and Serviceimpl writing//Writing three: Use service to get bean helloservice HelloService1 = (helloservice)

              Context.getbean ("Helloserviceimpl"); It can also be written like this: but generally not, because Java is all interface-oriented programming, so declare the type of the interface as much as possible instead of implementing the type Helloserviceimpl HELLOSERVICEIMPL1 = (helloserv

                            

              Iceimpl) Context.getbean ("Helloserviceimpl"); Writing four: The same use of service to get beans, the official website to write, the comparison of the specification HelloService HelloService2 = (helloservice) context.getbean ("Helloser

              Viceimpl ", Helloserviceimpl.class); It can also be written like this: but generally not, because Java is all interface-oriented programming, so declare the type of the interface as much as possible instead of implementing the type Helloserviceimpl HELLOSERVICEIMPL2 = (helloserv

                            

              Iceimpl) Context.getbean ("Helloserviceimpl", Helloserviceimpl.class); Helloservice2.sayhEllo ();

 

Helloserviceimpl class; It is the package Www.csdn.spring.service.impl in Serviceimpl that needs attention;

Import Www.csdn.spring.dao.HelloDao;

 

Import Www.csdn.spring.service.HelloService;

  public class Helloserviceimpl implements helloservice{private Hellodao Hellodao;

  Public Helloserviceimpl () {System.out.println ("Helloserviceimpl instantiation"); //set Dependency Injection is important, do not write an error, can not read and write Hellodao this attribute/* Org.springframework.beans.NotWritablePropertyException:Invalid P Roperty ' Hellodao ' of bean class */public void Sethellodao (Hellodao hellodao) {System.out. P Rintln ("Inversion of Control: the application itself is not responsible for creating Hellodao objects, but is created, managed, maintained by the spring container, so control transfers, called reversals."

         "+" can inject the Hellodao object "by means of a dependency injection");

  This.hellodao = Hellodao;

  @Override public void SayHello () {Hellodao.sayhello ();
 }

}

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.