Third, the IOC annotation based configuration
Article Directory
- Third, the IOC annotation based configuration
- 1, xml configuration form
- 2, annotation-based configuration
- 3.1 to create an object for the annotation
- Annotation data for injecting 3.2
- 3.3 scope for changing
- 3.4 and lifecycle-related
- 3.5 Comparison and Selection of annotations and xml
- 3, the configuration of the Notes to transform
- 3.1 instead of using the configuration profile class
- Multiple configurations class 3.2 project
- 3.3 Notes @ProPertySource
- 4, Spring integration Junit
Concept: Based on the xml configuration IOC configuration and functions implemented notes are the same.
1, xml configuration form
Xml configuration of the above summary, can be divided into the following four functions
- For creating an object
- Data for injection
- Scope for change
- And lifecycle
2, annotation-based configuration
3.1 to create an object for the annotation
- @Component
Role: Spring is to allow resources to manage, configure the xml equivalent to a bean.
Property: value: Specifies the id of the bean, if property value is not specified, the default bean id is the current class name. The first letter lowercase.
- @Controller、@Service、@Reporsitory
They are three notes for a derivative of the notes, their role and attributes are exactly the same. They simply provide a more explicit semantic.
@Controller: General performance for the annotation layer
@Service: general business for the annotation layer
@Repository: a persistence layer for the annotation
note: If there is one and only one annotation attribute to assign, and the name is value, value of the assignment is not written
Annotation data for injecting 3.2
Their role on the xml configuration file and bean tags to write a label that is in the same
- @AutoWired
Automatically according to the type of injection, as long as there is only one bean container object types and be injected variable type matching, can be successfully injected. If the IOC container without any type of bean and injection of variable types match, then an error.
It may act on variables, the method can also be applied to the
first look at the structure of the Map Value data types match , if match is injected directly into the data. Otherwise, look in the Key with the variable name matches the.
- @Qualifier
On the basis of the automatic injection according to the type, according to the bean id injection. It to the field implantation can not be independently used, and must be used with @Autowire, but when a parameter injection method, can be used independently.
Property: value: specifying the bean id.
@Autowired
@Qualifier("accountDao1")//查找注解为"accountDao1"的对象注解
private AccountDao accountDao;
- @Resource
Id according to the bean direct injection, it can also inject other bean types
Attribute: name: specifying the bean id
@Resource(name = "accountDao2")//查找注解为"accountDao2"的对象注解
private AccountDao accountDao;
Note: @ autowire, @ Qualifier, @ Resource injection can only other bean types, but the basic type String and can not be used to achieve these three notes, the collection type of injection only be achieved through xml .
@Value
Injection basic data types and data type String
Attribute: value: specifies values
3.3 scope for changing
@Scope
Specify the scope of the bean,
Attribute: value of the specified range, the value is: Singleton, prototype, request, session, globalsession
3.4 and lifecycle-related
- @PostConstruct: a designated initializer
- @PreDestory: used to specify the methods of destruction
3.5 Comparison and Selection of annotations and xml
Note: The configuration is simple, easy to maintain (we found the class, which is equivalent to find a position corresponding)
xml: When you modify, no need to change the source code, it does not involve recompiling and deploying
XML-based configuration | Annotation-based configuration | |
---|---|---|
Bean definition | @Component @Repository derived classes (persistence) @Service (business layer) @Controller (control layer) | |
Bean name | Specified by id or name | @Component(“person”) |
Bean injection | Or by p namespace | @Autowired (name by injection) @Qualifier (by type injection) |
Life processes, Bean of scope | init-method, destory-method; scope attribute range | @PostConstruct initialization @PreDestory destroy @Scope setting scope |
Applicable scene | Bean from a third party | Bean implementation class developed by the users themselves |
3, the configuration of the Notes to transform
Based springIOC configuration annotations, the bean-based features and objects of the xml configuration is exactly the same.
Note: If we use pure annotation configuration, we still want to use bean.xml profile
bean.xml configuration file still contains the following information
<context:component-scan base-package="com.simon"></context:component-scan>
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!--注入数据源-->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--配置数据库的必要信息-->
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&serverTimezone=UTC"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
3.1 instead of using the configuration profile class
- @Configuration
Role: The current class is used to specify a spring class configuration, will be loaded from the class notes when creating a container, you need AnnotationApplicationContext acquiring container (class .class @Configuration have annotated)
Attribute: value: for the configuration specified bytecode class
- @ComponenScan
Action: specifies the packet to be scanned. And a spring acting in the xml configuration file: <context: component-scan base-package = "com.simon" /> is the same
Properties: basePackage: specifies the packages to be scanned, and the value of the action attribute is the same annotation
- @Bean
Role: The only comment written on the method, this method creates a table object and stored into the Spring container
Attribute: name: to create objects in the current @Bean annotation method to specify a name (that is, the bean id)
@Configuration
@ComponentScan("com.simon")
public class SpringConfiguration {
@Bean(name = "queryRunner")
public QueryRunner createQueryRunner(DataSource dataSource) {
return new QueryRunner(dataSource);
}
@Bean(name = "dataSource")
public DataSource createDataSource() {
ComboPooledDataSource cbd = new ComboPooledDataSource();
try {
cbd.setDriverClass("com.mysql.cj.jdbc.Driver");
cbd.setJdbcUrl("jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT");
cbd.setUser("root");
cbd.setPassword("root");
return cbd;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Multiple configurations class 3.2 project
@Import
Action: class for introducing other configurations, other configurations based upon introduction, other configurations class @Configuration write can not write.
Attribute: value []: specifies other configuration class bytecode
-
Father configuration class
@Configuration @ComponentScan("com.simon") @Import(JdbcConfiguration.class) public class SpringConfiguration { }
-
Sub-class configuration
@Configuration public class JdbcConfiguration { @Bean(name = "queryRunner") public QueryRunner createQueryRunner(DataSource dataSource) { return new QueryRunner(dataSource); } @Bean(name = "dataSource") public DataSource createDataSource() { ComboPooledDataSource cbd = new ComboPooledDataSource(); try { cbd.setDriverClass("com.mysql.cj.jdbc.Driver"); cbd.setJdbcUrl("jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT"); cbd.setUser("root"); cbd.setPassword("root"); return cbd; } catch (Exception e) { throw new RuntimeException(e); } } }
3.3 Notes @ProPertySource
Used to load .properties file configuration. Such as when we configure the data source, information can be written to the database connection properties file
Attribute: value []: specifies the properties file location, if the class path, the need to add classpath
@PropertySource("classpath:jdbcConfig.properties")//在父类上添加该注解即可
-
jdbcConfig.properties profile
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT jdbc.username=root jdbc.password=root
-
jdbcConfiguration class
@Configuration public class JdbcConfiguration { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean(name = "queryRunner") public QueryRunner createQueryRunner(DataSource dataSource) { return new QueryRunner(dataSource); } @Bean(name = "dataSource") public DataSource createDataSource() { ComboPooledDataSource cbd = new ComboPooledDataSource(); try { cbd.setDriverClass(driver); cbd.setJdbcUrl(url); cbd.setUser(username); cbd.setPassword(password); return cbd; } catch (Exception e) { throw new RuntimeException(e); } } }
4, Spring integration Junit
- Problems facing the test, why reinvent the Junit
- Entry application (main Method)
- junit unit test, no main method can be performed, as a main junit integrated method will determine whether the current test classes which @Test annotation methods, let there junit Test method performed annotated
- junit not care whether we use the Spring framework, because in the implementation of the test method, junit do not know whether we use the Spring framework, so I will not read the configuration file for our / Spring core container class to create configuration
- Integration Steps
Introducing a spring integrated junit JAR (coordinates), i.e., spring-test
Annotations using a Junit provided to replace the existing main method, provided replaced @Runwith Spring
Inform the runner spring, spring and ioc creation is based on xml or annotation, location and description
@ContextConfiguration
locations: specify the location of the xml file, plus classpath keyword indicates the class path
@ContextConfiguration("classpath:bean.xml")
classes: Class notes designated location
@ContextConfiguration(classes = SpringConfiguration.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
private AccountService accountService;
@Test
public void testFindAll() {
List<Account> list = accountService.findAllAccount();
for (Account account : list) {
System.out.println(account);
}
}