Spring
1. Spring overview
Spring is an IOC(DI) and AOP container framework
2. Excellent features of Spring
(1) Non intrusive
(2) Control reversal: IOC
(3) Dependency injection: DI
(4) Aspect oriented: AOP extends its functions without modifying the source code
(5) Container: it contains and manages the declaration cycle of application objects
(6) Componentization: objects created by Spring can be combined through xml and annotations
(7) One stop: open source frameworks and third-party class libraries that can integrate various enterprise applications
**3. Through xml - setter injection**
In the bean tag, set the bean property value through property
- Name attribute: the name of the configuration bean attribute
- Value attribute: the attribute value of the configuration bean
- You can also configure the attribute value of the bean through the child tag of value
public class Book { private String name; private double price; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Book() { } @Override public String toString() { return "Book{" + "name='" + name + '\'' + ", price=" + price + '}'; } }
<?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 id="book" class="com.yhcen.spring.Book"> <property name="name" value="java From getting started to giving up"></property> <property name="price" value="200.00"></property> </bean> </beans>
@Test public void test(){ //Create IOC container ApplicationContext ioc = new ClassPathXmlApplicationContext("application.xml"); Book book = (Book)ioc.getBean("book"); System.out.println(book); }
4. Constructor injection
//1. Add a parameter construct to the entity bean public class Book { private String name; private double price; public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Book() { } public Book(String name, double price) { this.name = name; this.price = price; } @Override public String toString() { return "Book{" + "name='" + name + '\'' + ", price=" + price + '}'; } }
//Injection through constructor in bean <bean id="book2" class="com.yhcen.spring.Book"> <constructor-arg value="java From getting started to giving up"></constructor-arg> <constructor-arg value="2.2"></constructor-arg> </bean>
5. Introducing external bean s
Enter the external bean through ref
<bean id = "cart" class="com.yhcen.spring.Cart"> <property name= "book" ref = "book"></property> <property name= "count" value = "10"></property> <property name= "amount" value = "1000"></property> </bean>
6. Configure internal bean s
Internal beans cannot be referenced by other beans
<bean id = "cart" class = "com.yhcen.spring.Cart"> <property name = "book"> <bean class = "com.yhcen.spring.Book"> <property name="name" value="java From getting started to giving up"></property> <property name="price" value="200.00"></property> </bean> </property> <property name= "count" value = "10"></property> <property name= "amount" value = "1000"></property> </bean>
7. Cascade attribute assignment
<bean id= "cart" class = "com.yhcen.spring.Cart"> <property name= "book" ref = "book"></property> <property name = "book.name" value = "Water Margin"></property> <property name= "count" value = "10"></property> <property name= "amount" value = "1000"></property> </bean>
8. Automatic assembly
<!-- automatic assembly We can pass bean of autowire Attribute let spring Perform automatic assembly autowire Attribute description byName: Based on the attribute name (the attribute name in the entity class) id from IOC Search in the container and automatically assemble it after finding it. If it is not found, a null value will be displayed default and no Represents no assembly byType: According to attribute type and IOC In container bean To achieve automatic assembly, find one of this type bean Assembly is successful. Multiple exceptions are thrown. Assembly is not allowed if no exceptions are found --> <bean id = "cartItem4" class= "com.yhcen.spring.CartItem" autowire = "byName"> <property name= "count" value = "10"></property> <property name= "amount" value = "1000"></property> </bean> <bean id = "cartItem5" class= "com.yhcen.spring.CartItem" autowire = "byType"> <property name= "count" value = "10"></property> <property name= "amount" value = "1000"></property> </bean>
9. Configure data sources
<bean id = "dataSource" class = "com.alibaba.druid.pool.DruidDataSource"> <property name = "driverClassName" value = "com.mysql.jdbc.Driver"></property> <property name = "url" value = "jdbc:mysql://localhost:3306/db"></property> <property name = "username" value = "root"></property> <property name = "password" value = "11111"></property> </bean>
You can extract the configuration file druid.properties
jdbc.driverClassName = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/db jdbc.username = root jdbc.password = 11111
<!-- Introduce external properties file --> <context:property-placeholder location = "classpath:druid.properties"></context:property-placeholder> <bean id = "dataSource" class = "com.alibaba.druid.pool.DruidDataSource"> <property name = "driverClassName" value = "${jdbc.driverClassName}"></property> <property name = "url" value = "${jdbc.url}"></property> <property name = "username" value = "${jdbc.username}"></property> <property name = "password" value = "${jdbc.password}"></property> </bean>
10. Configuring bean factory based on xml
To create a factory bean, you need to implement the FactoryBean interface
(1) Import 5 basic jar packages of spring
(2) Create the XML file beans.xml
<!-- Configuration factory bean --> <bean id="myFactoryBean" class="com.yhcen.spring.MyFactoryBean"> </bean>
(3) Create factory bean to implement factorybean < >
public class MyFctoryBean implements FactoryBean<Book>{ @Override public Book getObject() throws Exception{ return new Book(9,"java The way to God","yhcen",80); } //Set return bean type @Override public class<?> getObjectType(){ return Book.class; } //Single case or not @Override public boolean isSingleton(){ return true; } }
(4) Test class get bean
public class SpringTest{ ApplicationContext ioc = new ClassPathXmlApplicationContext("beans.xml"); @Test public void testFactoryBean(){ Book book = (Book)ioc.getBean("myFactoryBean"); System.out.println(book); } }
11. Scope of the bean
(1) Create entity class
public class BeanScope{ private String name; //get;set method omitted }
(2) Create the XML configuration class file beans.xml
<!-- bean The scope of is through scope Property set scope: singletion : Default value, bean It's a single case, IOC Instantiate as soon as it is created bean prototype: Multi instance, IOC The container will not be created as soon as it is created bean object,Only call getBean Method will be created bean Object, and a new object is created without calling once request: every time Http Every request creates a new object session: Each new session creates a new object --> <bean id="beanScope" class="com.yhcen.spring.BeanScope" socpe="singletion"> <property name="name" value="test bean Scope of"></property> </bean>
(3) Testing
@Test public void testFactoryBean(){ BeanScope beanScope = ioc.getBean("beanScope"); BeanScope beanScope1 = ioc.getBean("beanScope"); //The object created by the two calls is different, but if it is a singleton, it is the same object }
12. The lifecycle of a bean
(1) Create a bean instance through a constructor or factory method
(2) Set the time value of the bean's properties and references to other beans
(3) bean usage
Init method = '': initialize method
Destruction method = "": destruction method (only when the container is closed)
So how do I close the ioc container?
ApplicationContext ioc = new ClassPathXmlApplicationContext("beans.xml"); ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext)ioc; configurableApplicationContext.close();
Create - attribute assignment - object initialization - use - Destroy
13. Create objects by annotation
(1)@Component identifies a component managed by IOC
(2) The @ repository identifies a persistence layer component managed by the IOC container
(3)@Service identifies a business logic layer component managed by the IOC container
(4)@Controller identifies a presentation layer component managed by the IOC container
");
ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext)ioc;
configurableApplicationContext.close();
establish--Attribute assignment-Object initialization---use - Destroy **13,Create objects by annotation** (1)@Component Identified a subject IOC Managed components (2)@Repository Identified a subject IOC Container managed persistence layer components (3)@Service Identified a subject IOC Container managed business logic layer components (4)@Controller Identified a subject IOC Presentation layer component of container management