Java and design patterns in Spring practice-collection
Spring practice
Labels: Java and Design Patterns
Junit Integration
Previously used multiple times@RunWith
And@ContextConfiguration
Add these two annotations to the test class, and the program will automatically load the Spring configuration and initialize the Spring container to facilitate the integration test between Junit and Spring. To use this function, add the following dependencies to pom. xml:
Pom. xml
org.springframework
spring-test
4.2.0.RELEASE
To
@RunWith
And
@ContextConfiguration
Load Spring containers
/*** Spring integrated Junit * Created by jifang on 15/12/9. * // @ RunWith (SpringJUnit4ClassRunner. class) @ ContextConfiguration (locations = "classpath: spring/applicationContext. xml ") public class BeanTest {@ Autowired private Bean; @ Test public void testConstruct () {Car car = bean. getCar (); System. out. println (car );}}
Web Integration
We can useServletContext
The uniqueness of the data stored by the container, andServletContextListener
Will be called only once during container initialization. ConfigureContextLoaderListener
To load the Spring configuration file/initialize the Spring container:
Pom. xml/spring-web
org.springframework
spring-web
4.2.0.RELEASE
Configure listeners (web. xml)
org.springframework.web.context.ContextLoaderListener
Load the Spring configuration file
contextConfigLocation
classpath:spring/applicationContext.xml
Appendix: git address of the complete web. xml file.
Test Servlet
@WebServlet(urlPatterns = "/servlet")public class Servlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); Bean bean = context.getBean("bean", Bean.class); Car car = bean.getCar(); System.out.println(car); }}
In applications, common JavaBean is managed by Spring and can be used@Autowired
Automatic injection. HoweverFilter
AndServlet
Except, they are all managed by Servlet containers, so their attributes cannot be injected using Spring. Therefore, Servlet is generally not directly used in actual projects, springMVC, WebX, Struts2, and other MVC frameworks are used to simplify development. A special blog will be provided to introduce such frameworks.
Note: Do not forget to add Servlet-api dependency when running servlet:
javax.servlet
javax.servlet-api
3.1.0
File loading 1. Introduce properties
You can put the attribute parameter values that need to be modified frequently in the properties file and introduce them in the Spring file.
Db. properties
## Data Sourcemysql.driver.class=com.mysql.jdbc.Drivermysql.url=jdbc:mysql://host:port/db?useUnicode=true&characterEncoding=UTF8mysql.user=usermysql.password=password
Note: No space is allowed after value.
1.1 property-placeholde Introduction
Use
Label to introduce the properties file.${key}
Reference, Java can be@Value("${key}")
Reference:
XML
Java
@Componentpublic class AccessLog { @Value("${mysql.url}") private String value; // ...}
1.2
PropertiesFactoryBean
Introduction
Spring providesorg.springframework.beans.factory.config.PropertiesFactoryBean
To load the properties file to facilitate the injection of properties property values in the JavaBean.
XML
classpath*:common.properties
Java
@Controllerpublic class Bean { @Value("#{commonProperties['bean.properties.name']}") private String name; // ...}
2. import other Spring configurations
If Spring has too many configuration items, you can divide the configuration by module into multiple configuration files (-datasource. xml/-dubbo-provider.xml/-bean. xml), which are configured by the masterApplicationContext. xmlFile Reference them, and now the labels can be introduced:
Transaction Management
Spring transaction management high-level abstraction mainly consistsPlatformTransactionManager
/TransactionDefinition
/TransactionStatus
Three interfaces are supported:
PlatformTransactionManager (Transaction Manager)
PlatformTransactionManager
The main function of Spring is transaction management. Spring provides differentPlatformTransactionManager
Implementation:
Transactions |
Description |
DataSourceTransactionManager |
JDBCTemplate/MyBatis/iBatis persistent use |
HibernateTransactionManager |
Persistent use of Hibernate |
JpaTransactionManager |
JPA persistent usage |
JdoTransactionManager |
Persistent use of JDO |
JtaTransactionManager |
JTA implements transaction management, which is used when a transaction spans multiple resources. |
Therefore, to use Spring to manage transactions, you must configure different transaction managers for different persistent layers.
TransactionDefinition (transaction definition Information)
TransactionDefinition
Provides related configurations for transactions, such as transaction isolation level/Propagation Behavior/read-only/Timeout:
Isolation level (isolation)
To solve the problem caused by transaction concurrency (dirty read/phantom read/non-repeated read), four isolation levels are introduced:
Isolation level |
Description |
DEFAULT |
Use the default database isolation level |
READ_UNCOMMITED |
Read not submitted |
READ_COMMITTED |
Read committed (Oracle default) |
REPEATABLE_READ |
Repeatable read (MySQL Default) |
SERIALIZABLE |
Serializing |
Propagation)
The Propagation Behavior is not a database feature, but to solve the problem that two transactions call each other at the business layer:
Propagation type |
Description |
REQUIRED |
Supports the current transaction. If the transaction does not exist, a new transaction is created (default) |
SUPPORTS |
Supports the current transaction. If the transaction does not exist, the transaction is not used. |
MANDATORY |
Supports the current transaction. If the transaction does not exist, an exception is thrown. |
REQUIRES_NEW |
If a transaction exists, a new transaction is suspended. |
NOT_SUPPORTED |
Run in non-transaction mode. If a transaction exists, the current transaction is suspended. |
NEVER |
Run in non-transaction mode. If a transaction exists, an exception is thrown. |
NESTED |
If the current transaction exists, the nested transaction is executed (onlyDataSourceTransactionManager Valid) |
Timeout read-only)
Read-only transactions that cannot be executed
INSERT
/
UPDATE
/
DELETE
Operation.
TransactionStatus)
Obtains the status of a time point during transaction execution. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4NCjwvYmxvY2txdW90ZT4NCjxociAvPg0KPGgzIGlkPQ = "declarative Transaction Management"> declarative Transaction Management
Spring declarative Transaction Management: No need to modify the original code. You only need to add the configuration (XML/Annotation) for Spring to add the transaction management function for the target code.
Requirement: transfer case (using MyBatis ).
AccountDAO
UPDATE account SET money = money + #{0} WHERE name = #{1};
UPDATE account SET money = money - #{0} WHERE name = #{1};
/*** @ Author jifang * @ since 16/3/3 am. */public interface AccountDAO {void transferIn (Double inMoney, String name); void transferOut (Double outMoney, String name );}
Service
public interface AccountService { void transfer(String from, String to, Double money);}
@ Service ("service") public class AccountServiceImpl implements AccountService {@ Autowired private AccountDAO dao; @ Override public void transfer (String from, String to, Double money) {dao. transferOut (money, from); // an exception is thrown here. No transaction will cause data inconsistency int a = 1/0; dao. transferIn (money, );}}
Mybatis-configuration.xml/applicationContext-datasource.xml
Com. mysql. jdbc. jdbc2.optional. MysqlDataSource
True
250
2048
ApplicationContext. xml (no transaction)
Client
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = "classpath:spring/applicationContext.xml")public class SpringClient { @Autowired private AccountService service; @Test public void client() { service.transfer("from", "to", 10D); }}
Executing the above Code will result in inconsistent data.
XML configuration
Spring transaction management depends on AOP, and AOP needs to define the aspect (Advice + PointCut). In Spring, the default Advice for transaction management is provided.org.springframework.transaction.interceptor.TransactionInterceptor
And Spring introduces the tx tag to simplify the transaction Configuration:
Introduce the tx namespace and configure Advice:
Configuration aspect
Spring transaction management (Advice) is based on SpringAOP, so we use
Configuration:
Annotation Configuration
By configuring transactions with annotations, You can omit the definition of the cut point (because the PointCut setting has been determined by the place where the annotation is placed). You only need to configure Advice:
Activate annotation Transaction Management
Add
@Transactional
Annotation
@Override@Transactional(transactionManager = "transactionManger", readOnly = true)public void transfer(String from, String to, Double money) { // ...}
You can@Transactional
Configure the same transaction attributes as XML (isolation/propagation, etc ).
Practice
We recommend that you use XML to configure transactions. In actual development, the transaction is generally configured and managed in a centralized manner. In addition, the isolation/propagation of the transaction is generally enough by default, but we need to configureRead-only or not(For example, in MySQL master-slave backup, the master database generally provides read and write operations, while the slave database only provides read Operations). Therefore, the configuration can be as follows:
Master/Slave