当前位置:网站首页>Review all frames before sum of SSM frames
Review all frames before sum of SSM frames
2022-07-25 02:52:00 【young_ man2】
One 、 Spring Frame review
1. Spring yes javaEE An application in the field of programming full-stack Lightweight open source framework , It contains IOC( Inversion of control ) and AOP( Section oriented programming ) These two cores ; Provide presentation layer (SpringMVC) And many enterprise application technologies such as business layer and persistence layer .
2. Spring The advantages of
- Easy decoupling , Simplify the development
- AOP Programming support
- Control of declarative transactions
- Convenient program testing
- Convenient integration of various excellent frameworks
- Reduce JavaEE API The difficulty of using
- Java Source code is a classic learning example
3. Development steps
① Import Spring Dependency needed (pom.xml)--- Import spring-context and spring-tx Dependence
② To write Dao Interface and implementation classes
③ Configure core files (applicationContext.xml)
④ stay Spring Configuration in profile UserDaoImpl
⑤ Use SpringAPI get Bean example
spring-context and spring-tx The difference between
spring-context:
yes Spring Context , You can find the use of Spring ApplicationContext All the classes required for a feature ,
UI Aspects are used with templates (Templating) The engine is like Velocity、FreeMarker Integrated classes , And calibration Validation Related aspects of the class .
spring-tx:
spring Provide support for transactions , The relevant transaction processing and implementation classes are here Jar In bag
The code is as follows
① Add dependency
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.17.RELEASE</version>
</dependency>
</dependencies>② Create persistence layer and business layer and their implementation
UserDao
public interface Userdao{
public void save();
}UserService
public interface UserService{
public void save();
}UserDaoImpl
public class UserDaoImpl implements UserDao{
private String username; //username Variable
private int age; //age Variable
// Set up username Value
public void setUsername(String username) {
this.username = username;
}
//set Method setting age Value
public void setAge(int age) {
this.age = age;
}
public void setUsername(String username, int age){
this.username=username;
this.age=age;
}
public UserDaoImpl() {
System.out.println("UserImpl establish ....");
}
@Override
/* To the interface UserDao The implementation of the */
public void save() {
System.out.println(username+"======"+age);
System.out.println("save running.....");
}
}UserServiceImpl
public class UserServiceImpl implements UserService {
private UserDao userDao;
// There are two ways to set an instance ,set And using parametric constructs !
public UserServiceImpl(UserDao userDao) {
this.userDao = userDao;
}
public UserServiceImpl() {
}
/*public void setUserDao(UserDao userDao){
this.userDao=userDao;
}*/
public void save() {
userDao.save();
System.out.println("running.....");
}
}③ Create core profile (applicationContext.xml) And configuration
【 I need to mention here , If you can't create Spring Config What should you do when ?
Check whether you add plug-ins , The steps are File-Settings-Plugins Search for Spring, If you didn't add it, please add it and restart idea
If you add , Please check whether your dependency is imported correctly ?
Note that the need is Spring-context Dependence ; He means context , It can be done to applicationContext.xml Import all files of
】
<?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">
<!-- First, import. Dao Layer configuration -->
<bean id="userDao" class="com.wxy.dao.UserDaoImpl">
<!-- This is the configuration of basic data -->
<property name="username" value="zhangsan"/>
<property name="age" value="12"/>
</bean>
<!-- Import persistence layer -->
<bean id="userService" class="com.wxy.service.UserServiceImpl">
<!-- there name From you UserServiceImpl Medium setUserDao-->
<!-- Because here is the reference of the object , So I quote the above UserDao-->
<property name="userDao" ref="userDao">
</bean>
<!-- Again , For reference, you can also use P How to label
First add p Introduction of labels
xmlns="http://www.springframework.org/schema/p"
http://www.springframework.org/schema/p http://www.springframework.org/schema/p/spring-p.xsd
p The use of labels is :
<bean id="userService" class="com.wxy.service.impl.UserServiceImpl" p:userDao-ref="userDao"></bean>
-->
<!--============================= Constructor mode =====================================-->
<!-- How to use constructors It depends on what you are in front of UserServiceImpl To realize userDao It uses a constructor -->
<!-- <bean id="userService" class="com.wxy.service.impl.UserServiceImpl">
<constructor-arg name="userDao" ref="userDao"></constructor-arg>
</bean>
-->
<!--============================== aggregate ====================================-->
<bean id="userDao" class="com.wxy.dao.impl.UserDaoImpl" >
<property name="strList">
<list>aa</list>
<list>bb</list>
</property>
<property name="strMap">
<map>
<entry key="u1" value-ref="user1"></entry>
<!-- Use here value-ref The reason is to quote Map Object of type -->
</map>
</property>
<property name="properties">
<props>
<prop key="p1" > ppp1 </prop>
</props>
</property>
</bean>
</beans>④ Write tests
public class Controller{
@Test
public void test(){
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService)app.getBean("userService");
userService.save();
}
}ApplicationContext Interface correlation analysis

4. Spring Configure data sources
(1) The role of data sources ( Connection pool --- For example, connect to the database and use jdbc)
① Improve program performance
② Instantiate the data source in advance , Initialize some connection resources
③ Get from the data source when using the connection resource
④ After use, return the connected resources to the data source
Common data sources :DBCP、C3P0、BoneCP、Druid etc.
Here are C3P0 and druid Two ways of data source configuration
The manual configuration code is as follows :
public class DataSourceTest{
//C3P0 Configuration of data source
@Test
public void test1(){
CombopooledDataSource dataSource=new CombopooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/girls?characterEncoding=UTF8&autoReconnect=true&useSSL=false");
dataSource.setUser("root");
dataSource.setPassword("");
// Access to resources
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
//Druid Configuration of data source
@Test
public void test2(){
DruidDataSource dataSource=new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/girls?serverTimezone=GMT%2B8");
dataSource.setUsername("root");
dataSource.setPassword("546871893wxy.");
DruidPooledConnection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}The above configuration method will be more complex , Because you want to modify the normalization of the relevant data in the database during the loading week, you need to find this class , Then modify your parameters , that , We can configure these data into a fixed file jdbc.properties in , Then load in the test class
jdbc.properties
jdbc.Driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/...
jdbc.username=root
jdbc.password=rootThen load in the test class
@Test
// Test manual creation c3p0 data source ( load properties The configuration file )
public void test3() throws Exception {
// Read configuration file
// Address relative to the class load path
ResourceBundle resourseBundle=ResourceBundle.getBundle("jdbc");
String driver=resourseBundle.getString("jdbc.driver");
String url=resourseBundle.getString("jdbc.url");
String name=resourseBundle.getString("jdbc.username");
String password=resourseBundle.getString("jdbc.password");
// Create data source objects , Set connection parameters
ComboPooledDataSource dataSource=new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(name);
dataSource.setPassword(password);
Connection connection=dataSource.getConnection();
System.out.println(connection);
connection.close();
}(2)Spring Configure data sources
With the previous foundation , We can create the following Spring Configure the data source
① Import Spring The basic dependence of
② establish Dao Interface
③ establish Spring Core profile
<?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="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/girls?serverTimezone=GMT%2B8"></property>
<property name="user" value="root"></property>
<property name="password" value=""></property>
</bean>
</beans>public void test4() throws Exception {
ApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = app.getBean(DataSource.class);
Connection connection=dataSource.getConnection();
System.out.println(connection);
connection.close();
}(3) stay Spring Add jdbc.properties
stay applicationContext.xml Add Context The namespace of , take jdbc.properties Just add it in
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=
"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Load external properites file -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
</beans>5. Spring Annotation development for

Previously, we used statements to develop , Here we use annotations for development
We will replace the statements we have written with annotations one by one
① Replace statement <bean id="userDao" class="com.wxy.dao.UserDaoImpl">
@Component("UserDao")② Replace statement <bean id="userService" class="com.wxy.service.UserServiceImpl">
@Component("UserService")③ Replace statement <property name="userDao" ref="userDao"></property>
@Autowired
@Qualifier("userDao")④ Last but not least applicationContext.xml Add this sentence to
<context:component-scan base-package="com.wxy"/>Only by scanning can we finally read the file we want UserDao、UserService、UserServiceImpl
6. Upgrade of annotation development
Clearly distinguish notes on different levels

take @Component("userService") It is amended as follows @Service("userService")
take @Component("userDao") It is amended as follows @Repository("userDao")
About notes @Autowired Annotation @Qualifier Use
If you use type to add , Just use @Autowired; But if you use id Add , You need to use @Autowired and @Qualifier These two annotations
You can use annotations @Resource(name=" ") Yes @Autowired and @Qualifier These two annotations are replaced
![]()
7. Spring New annotation development
@Configuration---- Indicate that this class is Spring A core configuration class of
@ComponentScan(" ")---- substitute sentence <context-component-scan base-package="com.wxy">
8. Spring Integrate Junit
In the original Junit Integrate Spring in , You need to use the following statements to load
ApplicationContext app= new AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService user = app.getBean(UserService.class);
resolvent
Give Way SpringJunit Responsible for creating Spring Containers , But you need to tell him the configuration file
It will need to be tested bean Inject directly into the test class
step :

① Import Spring-test Coordinates of
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.17.RELEASE</version>
</dependency>② Use @RunWith Replace the original run time
@RunWith(SpringJunit4ClassRunner.class)③ Use @ContextConfiguration Specify the configuration file or configuration class
@ContextConfiguration("classpath:applicationContext.xml")④ Use @Autowired Inject objects that need to be tested
⑤ Add tests
9. SpringJdbc Template Use
summary : yes Spring An object provided in the framework , It's about primordial triviality jdbc API Simple encapsulation of objects .spring It provides us with many operation template classes . such as : Operate on relational databases JdbcTemplate and HibernateTemplate
Development steps :
① Import Spring-jdbc and spring-tx( Indicates the relationship between transactions ) Coordinates of
② Create database tables and entities
③ establish Jdbc Template object
④ Perform database operations
public class JdbcTeplateTest {
@Test
// test JdbcTemplate Development steps
public void test1() throws PropertyVetoException {
// Create data source objects
ComboPooledDataSource dataSource=new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8");
dataSource.setUser("root");
dataSource.setPassword("546871893wxy.");
JdbcTemplate jdbcTemplate=new JdbcTemplate();
// Set the data source object Know where the database is
jdbcTemplate.setDataSource(dataSource);
// Perform the operation
int tom = jdbcTemplate.update("insert into account values(?,?) ", "tom", 5000);
System.out.println(tom);
}
}
10. Spring Transaction control for
First , We need to know the relevant concepts of transactions :
Transaction refers to a series of strict logical operations in a program , All operations must be successful , Otherwise, all changes made in each operation will be undone . It can be understood as : Is to deal with many things as one thing , It's like everyone in the same boat , Live together , To finish together .
Transactions are atomic 、 Isolation, 、 Uniformity 、 persistence
(1) Program transaction control
① Programming transaction control object
* PlatformTransactionManager( Platform transaction manager )
( Get the status information of the transaction 、 Roll back the transaction 、 Commit transaction )
* TransactionDefinition( Encapsulate transaction information )
( Get the isolation level of the transaction 、 Get the propagation behavior of transactions 、 Get timeout 、 Is it read-only )
* TransactionStatus( The state object of the transaction )
( Whether to store rollback points 、 Whether the transaction is complete 、 Whether the transaction is rolled back 、 Whether it's a new business )
(2) be based on XML Declarative transaction control for
Handle transactions declaratively . The declaration here refers to the declaration in the configuration file , Use in Spring The declarative transaction processing in the configuration file replaces the code processing transaction .
Platform transaction manager configuration → Configuration of transaction notification → Business AOP Weaving configuration
(3) Annotation based development
11. Spring Inherited from web layer
① add to servlet, indicate web Where is the floor , Indicate where the compiled bytecode file is
② Inherit in class Servlet The implementation of the HttpServlet
【 Because here will appear above the original Junit The problems in the process , So this time we need to add a listener Listener So that we can be in Web When app starts , Just load Spring Configuration file for , Create application context object ApplicatiotiContext, In storing it to the largest domain servletContext domain , In this way, the application context can be obtained from the domain anywhere ApplicationContext Object .】
12. spring Add context tools
Need to add dependencies spring-web
Two 、 Spring mvc
1. summary :Spring MVC It's based on Java The implementation of the M(moudle)V(vue)C Design model for request driven type of lightweight Web frame , Belong to SpringFrameWork Subsequent products of , Already integrated in Spring Web Flow in .
2. Springmvc Development steps
demand : Client initiates request , Server receives request , Execute logic and jump view
① Import SpringMVC Of jar package -- Use springmvc Need to add spring-webmvc Dependence
② To configure Servlet( Core controller DispathcerServlet)
③ To write POJO【 Habitual abbreviation is Controller】 And views
④ take Controller Use annotations to configure to Spring In the container (@Component/@Controller---- Used to instantiate on a class Bean)
⑤ Configure component scanning ( To configure Spring-mvc.xml Core profile )
⑥ Perform access tests 
3. spring mvc The implementation process of

4. Spring MVC Annotation analysis of
@RequestMapping
effect : Used to establish a request URL And the corresponding relationship between the processing method
Location :
Class , request URL First level access directory for . Words not written here , Equivalent to the root directory of the application .
On the way , request URL Secondary access directory for , And the use of classes @RequestMapping The annotated primary directory together forms the access virtual path
attribute :
value: Used to specify the requested URL. He and path Properties work the same
method: Used to specify how to request .
params: Used to set conditions that limit request parameters . Support simple expressions . Request parameters for key and value It must be as like as two peas.
【 such as :params={"accountName"}, Indicates that the request parameter must have accountName;params={"money!100"}, In the request parameter money It can't be 100】
边栏推荐
- Tp5.1 login configuration method of whether to login public functions (complete login case)
- How to communicate with aliens
- DOM node type
- Hyperchain hyperblockchain Shi Xingguo was interviewed by 36 krypton: the amount of customer cooperation consulting is doubling
- Dynamic programming -- Digital DP
- "Introduction to interface testing" punch in to learn day05: how can a testing framework support restful interfaces?
- Introduction to web security telent testing and defense
- Arthas case: dynamic update application logger level
- Wechat sports field reservation of the finished works of the applet graduation project (7) mid-term inspection report
- Explorer TSSD 2019 software installation package download and installation tutorial
猜你喜欢

How to take the mold for the picture of 1.54 inch TFT st7789 LCD screen

JS written test questions -- random numbers, array de duplication

JS written test -- regular expression

Introduction to web security telent testing and defense

6.0 cancellation of member registration verification code

2022-07-19: all factors of F (I): I are added up after each factor is squared. For example, f (10) = 1 square + 2 square + 5 square + 10 square = 1 + 4 + 25 + 100 = 130.

On Calc optimization of calcite

JS foundation -- data

Permanently mount the image steps

Pagoda workman WSS reverse proxy socket legal domain name applet chat remove port
随机推荐
My creation anniversary (3rd Anniversary)
Cookies and sessions
Flink's study notes
Pypi counts the number of Downloads
Common Oracle commands
Arduino + si5351 square wave generator
Digital business cloud: how to realize the application value of supplier SRM management system?
Ctfshow misc introduction
Method of adding kernel in Jupiter notebook
【C】 Advanced knowledge of file operation
Routing policy interferes with routing
New key points of ES6
StrError and PERROR
Classic network learning RESNET code implementation
H5 common positioning function package
JS written test -- regular expression
JS foundation -- hijacking of this keyword
Digital commerce cloud fine chemical industry management platform integrated informatization solution
Details of happens before rules
Physical experiment simulation