This article mainly for you to share on the Java programming configuration ideas of the detailed, I hope to learn Java friends to help
Java Programming Configuration Ideas
Springboot Although provides a lot of excellent starter help us to develop quickly, can be the particularity of the actual production environment, we still need to do custom operation to the default integration configuration, improve the control of the program, although you do not necessarily better than the official supply of starter. Last week because of work and decoration things, cause the blog is not normal update, afraid of stopping more will make people lazy, squeeze a little time to write a relatively simple article. After a chat about how I from the decoration of small white to the experience of getting started.
Technology : Configuration,componentscan,propertysource,enabletransactionmanagement,bean,value
Description : Only the configuration code is posted and the complete test code is on GitHub.
source : Https://github.com/ITDragonBl ...
Article Directory structure:
One, Java programming configuration
Prior to spring4.x, the basic configuration of the application typically uses the way XML is configured, and the way in which annotations are suggested in business logic. After the spring4.x, the official began to recommend the use of Java programming configuration to replace the XML configuration, which is why? What are the pros and cons of these two configurations?
Java programming Configuration and XML configuration
XML configuration Benefits: For our older programmers (┬_┬), XML is very kind, easy to use, easy to extend, and modifying application configuration parameters does not need to be recompiled.
The disadvantage of XML configuration: The reading and parsing of configuration files takes time, and the content of XML configuration file is too bloated and inconvenient to manage.
Advantages of Java Programming Configuration: its structure is clearer and more readable than the XML configuration, and it also saves time spent parsing XML.
Java Programming Configuration Disadvantages: Modifying application configuration parameters requires recompilation. In fact, is not a big problem, the actual production environment, the application configuration is generally not and dare not to modify.
Both have their own merits, considering that both spring4.x and Springboot are recommending the use of Java programming configuration, we should also conform to the trend of the times, you can not use, but you should understand!
Java Programming Configuration steps
First step: Create a configuration class, add a note configuration to the class name, tell Spring this is a configuration class that acts like an XML file
Second step: Load the external configuration file, add annotation Propertysource to the class name, specify the read path of the properties file
Step three: Get the application configuration property value, add the annotation value on the attribute variable, get the parameters in the configuration file through the ${} expression
Fourth step: Dependency Injection, add bean annotations on the method, or use Factorybean
The first and fourth steps of the grammar, the second chapter of the article detailed introduction. The second and third steps of the grammar, the third chapter of the article detailed introduction.
Import Javax.sql.datasource;import Org.springframework.beans.factory.annotation.value;import Org.springframework.context.annotation.bean;import Org.springframework.context.annotation.componentscan;import Org.springframework.context.annotation.configuration;import Org.springframework.context.annotation.propertysource;import Org.springframework.jdbc.core.jdbctemplate;import Org.springframework.jdbc.datasource.datasourcetransactionmanager;import Org.springframework.transaction.platformtransactionmanager;import Org.springframework.transaction.annotation.enabletransactionmanagement;import com.mchange.v2.c3p0.combopooleddatasource;/** * Spring Configuration class * Configuration data source, transaction management, Bean, Auto scan package * @author Itdragon */@Configuration Declares that the class is a configuration class @propertysource ({"Classpath:propertySource.properties"})//introduces external file @componentscan ("Com.itdragon")//Configure Automatic Path to scan package @enabletransactionmanagement//Open annotation-based transaction management function public class Applicationcontextconfig {@Value ("${data_user}" ) Private String Data_user; @Value("${data_pawd}") Private String data_pawd; @Value ("${data_driver}") Private String data_driver; @Value ("${data_jdbc_url}") Private String Data_jdbc_url; @Bean//Data source public DataSource DataSource () throws exception{combopooleddatasource DataSource = new combopooled DataSource (); Datasource.setuser (Data_user); Datasource.setpassword (DATA_PAWD); Datasource.setdriverclass (Data_driver); Datasource.setjdbcurl (Data_jdbc_url); return dataSource; } @Bean//JDBC Template public jdbctemplate JdbcTemplate () throws exception{jdbctemplate JdbcTemplate = new Jd Bctemplate (DataSource ()); return jdbctemplate; } @Bean//Transaction Management public Platformtransactionmanager TransactionManager () throws exception{return new DataS Ourcetransactionmanager (DataSource ()); }}
Transaction class
Import Java.util.list;import Java.util.map;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.stereotype.service;import Org.springframework.transaction.annotation.transactional;import Com.itdragon.dao.ITDragonDao; @Servicepublic class Itdragonserver { @Autowired (required=false) private Itdragondao Itdragondao; Public list<map<string,object>> FindAll () { return itdragondao.findall (); } @Transactional public void Updatenamebyid (String name, Long ID) { itdragondao.updateusernamebyid (name, id); System.out.println (0/0); Transaction Exception }}
Full code, please asynchronous GitHub
Second, component injection
A bean annotation resembles a label in an XML file <bean> , where the method name decorated by the bean annotation corresponds to <bean> the ID in the label, or the value of the ID is set by the Value property of the bean annotation. is heavily used in the springboot underlying code.
If you want to create the object after the container is started and get it directly from the container after use, nothing needs to be done because spring defaults to a single instance, that is, when the container is started, the object is created and saved to the container, and then retrieved from the container when it is used.
If you want the container to start and not create the object, but instead create it when it is used, and then save it to the container, the next time it is taken from the container, it can be implemented by lazy loading, that is, using lazy annotation adornments.
If you want the container to start without creating an object, but instead create it each time it is used, use a multiple-instance approach, which uses the Scope annotation, which has a value of prototype, which is @scope ("prototype").
If you want the container to start and then select the bean that needs to be injected according to the condition, you can use annotation conditional to judge that the Springboot is using the annotation.
Import Org.springframework.context.annotation.bean;import Org.springframework.context.annotation.ComponentScan; Import Org.springframework.context.annotation.componentscan.filter;import Org.springframework.context.annotation.conditional;import org.springframework.context.annotation.Configuration; Import Org.springframework.context.annotation.filtertype;import Org.springframework.context.annotation.Lazy; Import Org.springframework.stereotype.controller;import Com.itdragon.entity.itdragonentity;import com.itdragon.server.itdragonserver;/** * Knowledge Point two: Configure Automatic Scan package path * One, annotation Componentscan value setting automatically scans the path of the package * two, The excludefilters value of the annotation Componentscan sets the rule for scanning exclusions * 1), the excluded type is set by the annotation @filter, and type=annotation means that the exclusion is included in the annotations. Classes is a specific annotation, such as Controller,server,repository * III, annotation Componentscan the includefilters value set the scan to join the rule * 1), Turn off spring default scan by setting Usedefaultfilters=false all features to make includefilters effective * knowledge Point three: @Filter common interception type * one, Filtertype.annotation: According to annotations * Two, Filtertype.assignable_type: according to the given type, including its subclasses and implementation class * Three, Filtertype.custom: using custom rules * * First CompOnentscan annotations indicate that classes and Itdragonserver classes and their subclasses and implementation classes that are decorated by controller annotations are not scanned under a specified package * The second Componentscan annotation indicates that only classes decorated with controller annotations are scanned under a specified package * The third Componentscan annotation indicates that the class that satisfies the rule is not scanned under the specified package according to the custom interception rule */@Configuration @componentscan (value= "Com.itdragon", excludefilters={@Filter (Type=filtertype.annotation,classes={controller.class}), @Filter (type= Filtertype.assignable_type,classes={itdragonserver.class})//@ComponentScan (value= "Com.itdragon", includefilters={@Filter (Type=filtertype.annotation,classes={controller.class})},usedefaultfilters=false)//@ Componentscan (value= "Com.itdragon", excludefilters={@Filter (type=filtertype.custom,classes={ Itdragoncustomtypefilter.class})}) public class Itdragonconfig {/** * knowledge point one: Configuration Bean * One, the value of the annotation bean represents the bean's I D * Second, the value of the annotation Bean is not set, the method name represents the Bean's ID */@Bean (value= "Itdragonbean") public itdragonentity itdragonentity () { The method name is important, like the ID name of the XML, or you can redefine the return new itdragonentity ("Itdragon", "Configuration-password", 25) through @bean value values; }/** * Knowledge point four: ScopE Properties * @Scope, adjust scope, default Single instance * Singleton: Single instance: The IOC container is created after the object is placed in the IOC container and needs to be fetched from the container. * Prototype: Multiple instances: The object is created every time an IOC container is fetched. * Request: Create an instance at the same time * session: Create an instance of the same session * Knowledge point five: Lazy loading * For a single instance, the object is not created after the container starts, and the object is created the first time the bean is used. Can be understood as a supplement to a single instance. * *///@Scope ("prototype") @Lazy @Bean public itdragonentity Scopetopicbean () {System.out.println ("^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^create beans"); return new Itdragonentity ("Scopebean", "Singleton-prototype-request-session", 25); }/** * Knowledge point Six: Conditional condition judgment * satisfies a condition to register a bean, can be decorated on a class, and manages component injection under the entire class. */@Bean @Conditional ({itdragoncustomcondition.class}) public itdragonentity Conditionalbean () {return NE W itdragonentity ("Conditionalbean", "Conditional-condition-customcondition", 25); }/** * Knowledge point seven: Factorybean factory bean * Factorybean default to set single and multi-instance by calling Issingleton by invoking the object created by GetObject. */@Bean public Itdragonfactorybean Itdragonfactorybean () {return NEW Itdragonfactorybean (); }}
Custom conditional Judgment Component injection class
Import Org.springframework.beans.factory.support.beandefinitionregistry;import Org.springframework.context.annotation.condition;import Org.springframework.context.annotation.ConditionContext Import org.springframework.core.type.annotatedtypemetadata;/** * Custom conditional judgment Component Injection * @author Itdragon * */public class Itdragoncustomcondition implements condition{ /** * Determine if the registered bean contains the specified bean */public Boolean matches (Conditioncontext context, annotatedtypemetadata metadata) { //Get the Bean's registration class Beandefinitionregistry registry = Context.getregistry (); Return registry.containsbeandefinition ("Scopetopicbean"); There is load Conditionalbean }}
Factory Class for custom beans
Import Org.springframework.beans.factory.factorybean;import com.itdragon.entity.itdragonentity;/** * Factory class for custom Bean * @ Author Itdragon * */public class Itdragonfactorybean implements factorybean<itdragonentity>{public Itdragonentity GetObject () throws Exception { System.out.println ("^^ ^^ ^^ ^^ ^^ ^^ the ^^ ^^ ^^ ^^ ^factorybean Create Bean") ; return new itdragonentity (); Create the object and return to the container } public class<?> Getobjecttype () { return itdragonentity.class; } public Boolean Issingleton () { return false;//Set multiple instances, true as Singleton }}
Third, attribute assignment value
Property Assignment Steps:
The first step: introduce external files via annotations Propertysource. Can introduce multiple, if you worry that the file does not exist, can be ignored by the parameter Ignoreresourcenotfound setting
The second step: Get values from an external file by annotating value, generally in ${} format, also support #{} Spel expressions, or you can pass strings directly. If you want to receive some complex values, such as collections, you might consider using annotation configurationproperties, which will detail the pros and cons of both.
Import Org.springframework.beans.factory.annotation.value;import Org.springframework.context.annotation.Bean; Import Org.springframework.context.annotation.configuration;import Org.springframework.context.annotation.propertysource;import com.itdragon.entity.itdragonentity;/** * Knowledge Point One: introduction of external files , and get the value from the file * @PropertySource introduce external files, support multiple, if the file does not exist will error, you can set the parameter ignoreresourcenotfound=true Ignore * @Value from the external file to get the value, Supports Spel expressions, #{},${},string * @author Itdragon */@Configuration @propertysource (value={"classpath: Propertysource.properties "," classpth:xxx.properties "},ignoreresourcenotfound=true) public class Itdragonconfigvalue {@Value ("${account}")//Get data from configuration file private String account; @Value ("${password}") Private String PASSWORD; @Value ("${age}") Private Integer age; @Value ("Itdragon")//general assignment private String str; @Value ("#{(1+2-3)/4*5}")//arithmetic operation private String operator; @Value ("#{1>2 | | 2 <= 3} ")//relational Operation Private Boolean CoMparison; @Value ("#{systemproperties[' Java.version '}")//System configuration: Os.name private String systemproperties; @Value ("#{t (Java.lang.Math). ABS (-18)}")//Expression private String mapexpression; The @Bean ("Valuebean") public itdragonentity itdragonentity () {System.out.println ("^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^", ^^ the ^^ str: "+ S TR); System.out.println ("^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ Operator:" + operator); System.out.println ("^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ Comparison:" + comparison); System.out.println ("^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ systemproperties:" + systemproperties); System.out.println ("^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ ^^ mapexpression:" + mapexpression); return new Itdragonentity (account, PASSWORD, age); }}
Iv. Idle Learning
This is not about learning a technology, but about the importance of developing a learning habit. Freshman period, because of fear of not finding a job and reported an online training institutions. Often brainwashed, one of the words I was impressed with----"Make Excellence a Habit". Listen to my blood boiling. It took five thousand or six thousand oceans to sign up and later found it free on the internet .... individuals are not recommended to attend training .
This money is worth, "let good become a habit", this sentence to my influence is very big, from university to work, whenever encounter unfamiliar knowledge, and did not choose to escape it. Instead, take the time to find information from the Internet, learn, organize, practice until you understand it. But I never thought, this kind of study spirit actually used to decorate on .... Maybe learning is already a habit of mine !
At first, I was a decoration small white, do not know what is all-inclusive, half-pack, clear package; Do not know what is hard-installed, soft-installed, do not know the process of decoration; do not know the brand choice of water and electricity lines, cabinets, sanitary ware, do not know the advantages and disadvantages of hanging machine, cabinet machine, air duct , not to mention that a renovation to seven thousand or eight thousand. In the face of these unknown fields, I am unable to cope. I know clearly: if you do not understand, you are the chopping block on the fish, trampled.
Now, I find the answer on the platform of Baidu, know, rabbit and rabbit, and organize the content in markdown format! I was frightened by myself. Not only that, I still rob the designers of the rice bowl, DIY design. In the process of production, found a lot of unreasonable ideas. Glad to ask yourself to design a set, otherwise there are a lot of useless, time-consuming, power consumption, consumption of money. Mom and Dad and the female ticket is the customer, and I have been in the change! Change! Change! The stage. Experience the bitterness of a front-end engineer.
Who am I? Where am I? What am I doing?
I am a programmer, I am on the road of learning, I am doing to improve their own things!
Related recommendations: