当前位置:网站首页>SSM framework learning
SSM framework learning
2022-07-24 17:46:00 【Bobo toilet cleaning spirit】
spring Two core technologies IoC AOP
Spring It can integrate most of the frameworks on the market
MyBatis
MyBatis-plus
Struts
Struts2
Hibernate
Spring The official website shows Spring Technology included , To this day ,Spring A development ecosystem has been formed ,Spring Several items provided , Each project is used to complete a specific function .
Project learning sequence :
Spring Framework: As the underlying architecture , Foundation of operation
Spring Boot: Simplify the development , Speed up development
Spring Cloud: Distributed development tools
Spring The history of :Spring1.0 to Spring5.0
Spring4.0 Architecture diagram

IoC(Inversion of Control: Inversion of control )
In current code writing , The coupling between the business layer and the data layer is on the high side

Data layer definition class (BookDaoImpl) Inherited from interface (BookDao), Class defines the method of implementation (save), An object of the instantiation class of the business layer (bookdao), Object call method .
But if the implementation method in the class changes (BookDaoImpl), At this time, the business layer code needs to be changed , Redeployment is required at this time , compile .
IoC The idea is : When using objects , By initiative new The generated object is converted to an externally provided object , In this process, the control of the object is transferred from the program to the outside , This idea is called control reversal
Spring Technical right IoC Implemented
IoC,IoC Containers ,Bean,DI(Dependency Injection: Dependency injection )

IoC The goal is to fully decouple
IoC Container and DI Is the means of realization
IoC The effect is : When using objects, you can not only directly from IoC Get... In the container , And get bean All dependencies have been bound
IoC Introductory cases
1. Import Spring Coordinates of Spring-context, Corresponding version ,pom.xml Import in file dependency

2. establish Spring The configuration file , stay resource Folder

3. obtain IoC Containers , obtain Bean

DI Introductory cases
5. Delete the implementation class to use new Method generated object

6. Then there is no object , Use setter Method to create an object

7. Configure in profile Bean The relationship between

name and ref Although the same , But the meaning of the two is different ,name Represents the name of the attribute of the current implementation class , The function is to find bookDao Properties of , And call setter Method for object injection ,ref Represents Bean Of id, The function is to make Spring stay IoC Found in the container id yes bookDao Of bean object , to bookService Inject bookDao object

Bean Basic configuration
bean Of id Must be unique
bean Of name attribute : You can use multiple aliases
obtain bean Can pass id,name To get

bean The scope of action of
IoC The default object in the container is singleton , The same bean The created object is the same address , It's the same .
If you want to create a non singleton object , It needs to be modified bean Of scope attribute
scope Property defaults to singleton( Single case )

Set the property to prototype after , One bean The two objects created are two objects .
bean This singleton property of is suitable for objects that need to be reused
bean The instantiation process ( How do containers create objects )
1. Use construction methods to create objects
Spring Reflection is enabled at the bottom , Even if the constructor in the class is private Attribute , You can also access . Note that the constructor must be parameterless , otherwise Spring There will be errors when accessing methods . This method is very common
2. Use static factory instantiation
Factory : Use factories to create objects , Create a factory class , And define a static method
// Static factory creates objects
public class OrderDaoFactory {
public static OrderDao getOrderDao(){
return new OrderDaoImpl();
}
}Create an object using a static factory
public class AppForInstanceOrder {
public static void main(String[] args) {
// Creating objects through static factories
OrderDao orderDao = OrderDaoFactory.getOrderDao();
orderDao.save();
}
}stay Spring How to use static factory in
stay Spring Add the following content to the configuration file , If you don't join factory-method, Then only one factory object , Can't produce what we want orderDao object

class: Full name of factory class factory-mehod: The method name of the object created in the concrete factory class

This method can add other business operations in the factory , These operation methods are more convenient , If it's just ourselves new A new object comes out , Can only new An object , Unable to perform business operations . The static factory method is mainly common in the previous old system operation , At present, you can
Example factory and Spring Manage example factories
Similar to static factory , Create a factory class , But provide a Example method ,
public class UserDaoFactory {
public UserDao getUserDao(){
return new UserDaoImpl();
}
}Create a running class , Create an instance factory object in the class , Then create an object through the instance factory object
public class AppForInstanceUser {
public static void main(String[] args) {
// Create an instance factory object
UserDaoFactory userDaoFactory = new UserDaoFactory();
// Create objects from instance factory objects
UserDao userDao = userDaoFactory.getUserDao();
userDao.save();
}How to create classes through the instance factory Spring To implement?
stay Spring Add the following code to the configuration file


In the run class , Run the following code , From IoC Take out the corresponding bean
public class AppForInstanceUser {
public static void main(String[] args) {
ApplicationContext ctx = new
ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) ctx.getBean("userDao"); // stay IoC Find id by userDao Of bean, next Spring The management example chemical plant is running
userDao.save();
}
}Spring The management of chemical plants is still troublesome
therefore Spring In order to simplify this configuration, a method called FactoryBean To simplify development
FactoryBean
// Create a class implementation FactoryBean Interface
public class UserDaoFactoryBean implements FactoryBean<UserDao> {
// Instead of creating objects in the original instance factory
public UserDao getObject() throws Exception {
return new UserDaoImpl();
}
// Returns the name of the created class Class object
public Class<?> getObjectType() {
return UserDao.class;
}
}
It looks similar to the method of the example factory , But in Spring The difference between the two can be seen in the configuration file , Use FactoryBean The configuration code of the mode is much simpler

FactoryBean There are three methods in the interface
T getObject() throws Exception; //:getObject(), After being rewritten , Create the object in the method and return
Class<?> getObjectType(); //getObjectType(), After being rewritten , The main return is the... Of the created class Class object
default boolean isSingleton() {
return true;
}
// Not rewritten , Because it has been given the default value , It can be seen from the method name that its function is to set whether the object is a singleton , Default true This is a single example
This method is widely used . Very practical
bean Life cycle of
establish bean after , by bean The control method of adding life cycle is as follows
bean After creating , Want to add content , For example, resources needed for initialization
bean Before destruction , Want to add content , For example, it is used to release the resources used
public class BookDaoImpl implements BookDao {
public void save() {
System.out.println("book dao save ...");
}
// Express bean Initialize the corresponding operation
public void init(){
System.out.println("init...");
}
// Express bean Corresponding operations before destruction
public void destory(){
System.out.println("destory...");
}
}Add a lifecycle to the configuration file
<bean id="bookDao" class="com.itheima.dao.impl.BookDaoImpl" init-method="init"
destroy-method="destory"/>After running the run file , give the result as follows
As can be seen from the results ,init Method executed , however destroy Method is not executed , Why is that ?
Spring Of IOC The container is running on JVM in function main After the method ,JVM start-up ,Spring Load the configuration file to generate IOC Containers , Get from the container bean object , Then adjust the method to execute base note. ,main After method execution ,JVM sign out , This is the time IOC In container bean It was over before it could be destroyed So the corresponding... Is not called destroy Method
How can I call destory() Methods?
Provide the following methods
close Closed container
ApplicationContext There is no close Method
Need to put ApplicationContext Replace it with ClassPathXmlApplicationContext
ClassPathXmlApplicationContext ctx = new
ClassPathXmlApplicationContext("applicationContext.xml");Call again ctx Of close() Method
ctx.close()Then run the file ,destory Content in can be run

Register the hook to close the container
Before the container is closed , Set the callback function in advance , Give Way JVM Call this function back before exiting to close the container
call ctx Of registerShutdownHook() Method


The two methods have the same effect , Can close the container
Difference :close() Is to close when calling ,registerShutdownHook() Is in JVM Top note is closed before exiting. .
But add initialization and destruction code to the class , And then Spring Add configuration in , More trouble , therefore Spring Two interfaces are provided in to realize the above operations , You do not need to configure init and destory To configure

stay BookServiceImpl Add two interfaces to the class
public class BookServiceImpl implements BookService,InitializingBean,
DisposableBean // Implementation method of two interfaces
@Override
public void destroy() throws Exception {
System.out.println("Service destory");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Service init");
}After running ,


边栏推荐
- ROC and AUC details of the recommended system
- List of stringutils and string methods
- Trends of semiconductor industry
- Memory allocation and recycling strategy
- 2022 ranking list of database audit products - must see!
- 获取1688app上原数据 API
- Six ways for JS to implement inheritance
- MySQL数据库的一个问题
- new也可以创建对象,为什么需要工厂模式?
- 使用matplotlib模拟线性回归
猜你喜欢

The results of the second quarter online moving people selection of "China Internet · moving 2022" were announced

Wrote a few small pieces of code, broke the system, and was blasted by the boss

Tensorflow introductory tutorial (38) -- V2 net

C语言自定义类型 — 枚举

获取同程(艺龙)酒店数据

Quickly complete the unit test junit4 setting of intelij idea

Heuristic merging (including examples of general formula and tree heuristic merging)

2022 Yangtze River Delta industrial automation exhibition will be held in Nanjing International Exhibition Center in October

Review and analysis of noodle dishes

0630~职业素养课
随机推荐
[spoken English] 01 - Introduction to atom
Dry goods | three sub domain name collection tools worth collecting
Two dimensional convolution -- use of torch.nn.conv2d
Link editing tips of solo blog posts illegal links
700. Search DFS method in binary search tree
仅需一个依赖给Swagger换上新皮肤,既简单又炫酷!
1688/阿里巴巴按关键字搜索新品数据 API 使用说明
Eth POS 2.0 stacking test network pledge process
Preliminary study of Oracle pl/sql
pinia 入门及使用
Six ways for JS to implement inheritance
邻接表的定义和存储以及有向图无向图的邻接存储
JS & TS learning summary
C语言自定义类型讲解 — 结构体
生信常用分析图形绘制02 -- 解锁火山图真谛!
Make good use of these seven tips in code review, and it is easy to establish your opposition alliance
PXE高效批量网络装机
C # print reports using fastreport.net
深入解析著名的阿里云Log4j 漏洞
Can Lu Zhengyao hide from the live broadcast room dominated by Luo min?