I love Java Series --- [Spring annotation configuration based on the full IOC]

to sum up:

  1. @Configuration:

    Role: The current class is used to specify a spring class configuration, will be loaded from the class notes when creating container. When the vessel is required to obtain
         AnnotationApplicationContext (@Configuration have annotated class .class).
    Attribute:
      value: for the configuration specified bytecode class

Sample code:
 / ** 
* Spring configuration class, a file corresponding to bean.xml 
* @Version 1.0 
* / 
@Configuration 
public  class SpringConfiguration { 
} 
Note: 
We have to replace a configuration file with the class, but how the container when creating configuration to scan the bag? 
Look at a comment.

 

   2. @ComponentScan

    Action:
      specifies the spring when the initialization container to scan packages. And a spring acting in the xml configuration file:
      <context: Component Base-Package-Scan = "com.itheima" /> is the same.
    Properties:
      basePackages: specifies the packet to be scanned. The role and value of the property in the same comment.

Sample code:
 / ** 
* Spring configuration class, a file corresponding to bean.xml 
* @Version 1.0 
* / 
@Configuration 
@ComponentScan ( "com.itheima" )
 public  class SpringConfiguration { 
} 
Note: 
We have configured to be scanned package, but how the data source and QueryRuner objects removed from the configuration file it? 
Look at a comment.

  3. @Bean

     effect:

      The only written comment on the method, showed that create an object using this method, and spring into the container. 
    Attribute: 
      name: to create objects in the current @Bean annotation method to specify a name (that is, the bean id).
Sample code:
 / * 
* class connection configuration database 
* @author horse programmer 
* @Company http://www.ithiema.com 
* @Version 1.0 
* / 
public  class JdbcConfig {
 / ** 
* Create a data source, and spring into the vessel 
* @return 
* / 
@Bean (name = "the dataSource" )
 public the DataSource CreateDataSource () {
 the try { 
ComboPooledDataSource DS = new new ComboPooledDataSource (); 
ds.setUser ( "the root" ); 
ds.setPassword ( "1234 " ); 
ds.setDriverClass ( " com.mysql.jdbc.Driver "); 
Ds.setJdbcUrl ( "JDBC: MySQL: /// spring_day02" );
 return DS; 
} the catch (PropertyVetoException E) {
 the throw  new new a RuntimeException (E); 
} 
} 
/ ** 
* Create a QueryRunner, and also stored in the spring container 
* @param the dataSource 
* @return 
* / 
@Bean (name = "Runner" ) 
@Scope ( "the prototype" )
 public QueryRunner createQueryRunner (the DataSource the dataSource) {
 return  new new QueryRunner (the dataSource); 
} 
} 
Note: 
we have data sources and QueryRunner removed from the configuration file, then you can delete the bean.xml.
But because there is no configuration file, create a data source configuration and are coded into the class. How to configure them out of it? 
Look at a comment.

  4 .@PropertySource

  Role:
    used to load .properties file configuration. For example, we configure the data source, the information can be written to the database connection
    properties configuration file, you can use this annotation to specify the location of the configuration file properties.
  Attribute:
    value []: specifies the file location properties. If you are in the class path, you need to write on the classpath:

Sample code: 
Configuration: 
/ ** 
* connection configuration class database 
* @Version 1.0 
* / 
@PropertySource ( "CLASSPATH: jdbcConfig.properties" )
 public  class JdbcConfig { 
@Value ( "jdbc.driver $ {}" )
 Private String Driver ; 
@Value ( "jdbc.url $ {}" )
 Private String URL; 
@Value ( "jdbc.username $ {}" )
 Private String username; 
@Value ( "jdbc.password $ {}" )
 Private String password;
 / ** 
* Create a data source and stored in the spring container 
* @return 
* / 
@Bean (name="dataSource")
public DataSource createDataSource() {
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass(driver);
ds.setJdbcUrl(url);
ds.setUser(username);
ds.setPassword(password);
return ds;
} catch (PropertyVetoException e) {
throw new RuntimeException(e);
}
}
}
jdbc.properties 文件:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_day02
jdbc.username=root 
jdbc.password = 1234 
Note: 
At this point we have two class configuration, but they have no relationship. How to build their relationship? 
Look at a comment.

  5 .@Import

    Effect:
      for introducing classes other configurations, other configurations when introduced class, can not write @Configuration annotations. Of course, the writing did not ask
      questions.
    Attribute:
      value []: specifies the class bytecode other configurations.

 

Sample Code: 
@Configuration 
@ComponentScan (basePackages = "com.itheima.spring" ) 
@Import ({JdbcConfig. Class })
 public  class SpringConfiguration { 
} 
@Configuration // write lines are not written 
@PropertySource ( "classpath: jdbc.properties " )
 public  class JdbcConfig { 
} 
Note: 
we have to be configured are configured, but a new problem has arisen because there is no configuration file, and how to get the container it? 
See the next section.

 

  6. acquiring container through annotations 

ApplicationContext ac = 
new AnnotationConfigApplicationContext(SpringConfiguration.class);

 

  7. drawing engineering structures

 

Here is the scenario illustrates:

1. Create a maven project and import coordinates

 1 <dependencies>
 2     <dependency>
 3       <groupId>junit</groupId>
 4       <artifactId>junit</artifactId>
 5       <version>4.12</version>
 6       <scope>test</scope>
 7     </dependency>
 8 
 9     <!--spring单元测试-->
10     <dependency>
11       <groupId>org.springframework</groupId>
12       <artifactId>spring-test</artifactId>
13       <version>5.0.2.RELEASE</version>
14     </dependency>
15 
16     <!-- spring框架 -->
17     <dependency>
18       <groupId>org.springframework</groupId>
19       <artifactId>spring-context</artifactId>
20       <version>5.0.2.RELEASE</version>
21     </dependency>
22 
23     <dependency>
24       <groupId>commons-dbutils</groupId>
25       <artifactId>commons-dbutils</artifactId>
26       <version>1.4</version>
27     </dependency>
28 
29     <dependency>
30       <groupId>mysql</groupId>
31       <artifactId>mysql-connector-java</artifactId>
32       <version>5.1.26</version>
33     </dependency>
34 
35     <dependency>
36       <groupId>com.alibaba</groupId>
37       <artifactId>druid</artifactId>
38       <version>1.0.9</version>
39     </dependency>
40   </dependencies>

2.创建数据库和编写实体类

 1 public class Account {
 2 
 3   private long id;
 4   private String name;
 5   private String password;
 6   private long money;
 7 
 8 
 9   public long getId() {
10     return id;
11   }
12 
13   public void setId(long id) {
14     this.id = id;
15   }
16 
17 
18   public String getName() {
19     return name;
20   }
21 
22   public void setName(String name) {
23     this.name = name;
24   }
25 
26 
27   public String getPassword() {
28     return password;
29   }
30 
31   public void setPassword(String password) {
32     this.password = password;
33   }
34 
35 
36   public long getMoney() {
37     return money;
38   }
39 
40   public void setMoney(long money) {
41     this.money = money;
42   }
43 
44   @Override
45   public String toString() {
46     return "Account{" +
47             "id=" + id +
48             ", name='" + name + '\'' +
49             ", password='" + password + '\'' +
50             ", money=" + money +
51             '}';
52   }
53 }

 

3.使用注解配置持久层

 1 @Component("accountDao")
 2 public  class AccountDaoImpl implements AccountDao {
 3     @Autowired
 4     private QueryRunner queryRunner;
 5 
 6 
 7     //1.增加账户
 8     public int save(Account account){
 9         String sql ="insert into account values (null,?,?,?) ";
10         try {
11          return   queryRunner.update(sql,account.getName(),account.getPassword(),account.getMoney());
12         } catch (SQLException e) {
13             throw new RuntimeException(e);
14         }
15     }
16 
17     //2.根据id查询账户信息
18     @Override
19     public Account findById(int id) {
20         String sql ="select * from account where id=?";
21         try {
22             return queryRunner.query(sql,new BeanHandler<>(Account.class),id);
23         } catch (SQLException e) {
24             throw new RuntimeException(e);
25         }
26     }
27 }

4.使用注解配置业务层

 1 @Service
 2 public class AccountServiceImpl implements AccountService {
 3     @Resource(name="accountDao")
 4     private AccountDao accountDao;
 5 
 6 
 7     //1.增加账户
 8     @Override
 9     public int save(Account account) {
10 
11        return accountDao.save(account);
12     }
13 
14     //2.根据id查询账户
15     @Override
16     public Account findById(int id) {
17         return accountDao.findById(id);
18     }
19 }

5.创建并编写配置类

1 //主配置文件
2 @ComponentScan({"com.itheima.service","com.itheima.dao"})
3 @Import(DaoConfig.class)
4 public class Config {
5 
6 }
 1//子配置文件
@PropertySource("classpath:db.properties") 2 public class DaoConfig { 3 @Value("${jdbc.driver}") 4 private String driver; 5 @Value("${jdbc.url}") 6 private String url; 7 @Value("${jdbc.username}") 8 private String username; 9 @Value("${jdbc.password}") 10 private String password; 11 @Bean 12 public QueryRunner getQueryRunner(DataSource dataSource) { 13 QueryRunner queryRunner = new QueryRunner(dataSource); 14 return queryRunner; 15 } 16 17 @Bean 18 19 public DataSource getDataSource() { 20 DruidDataSource dataSource = new DruidDataSource(); 21 dataSource.setDriverClassName(driver); 22 dataSource.setUrl(url); 23 dataSource.setUsername(username); 24 dataSource.setPassword(password); 25 return dataSource; 26 } 27 }
1 #db.properties文件
2 jdbc.url=jdbc:mysql:///heima?characterEncoding=utf-8
3 jdbc.driver=com.mysql.jdbc.Driver
4 jdbc.username=root
5 jdbc.password=root

6.测试类

 1 public class AppTest {
 2 
 3 
 4     @Test
 5     public void test() {
 6         AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
 7         AccountService accountService = context.getBean(AccountService.class);
 8 
 9         Account user = accountService.findById(2);
10         System.out.println(user);
11 
12     }
13 }

 

Guess you like

Origin www.cnblogs.com/hujunwei/p/11135944.html