私は、Javaのシリーズを愛し--- [フルIOCに基づく春の注釈の設定]

要約:

  1. @Configuration:

    役割:現在のクラスは、春のクラス構成を指定するために使用されるコンテナを作成するときに、クラスのノートからロードされます。容器を得るために必要とされるとき
         AnnotationApplicationContextを(@Configurationは、クラスの.classを注釈を付けています)。
    属性:
      値:設定指定されたバイトコードのクラスのための

サンプルコード:
 / ** 
* Spring構成クラス、bean.xmlに対応するファイル
* @Version 1.0 
* / 
@Configuration 
パブリック クラスSpringConfiguration { 
} 
注:
私たちはクラスで設定ファイルを置き換える必要がありますが、どのようにコンテナの構成を作成するとき袋をスキャンするには?
コメントを見てください。

 

   2. @ComponentScan

    処置:
      初期化コンテナがパッケージをスキャンする際に、スプリングを指定します。XML設定ファイルに作用するばね:
      <コンテキスト:コンポーネントベース・パッケージ・スキャン=「com.itheima」/>は同じです。
    プロパティ:
      basePackages:スキャンするパケットを指定します。同じコメントのプロパティの役割と価値。

サンプルコード:
 / ** 
* Spring構成クラス、bean.xmlに対応するファイル
* @Version 1.0 
* / 
@Configuration 
@ComponentScan( "com.itheima" パブリック クラスSpringConfiguration { 
} 
注:
我々は、スキャンされるように構成されていますパッケージが、どのようにデータソースとQueryRunerオブジェクト設定ファイルから削除それは?
コメントを見てください。

  3. @Bean

     役割:

      この方法でのみ書き込まれたコメントは、容器内にこの方法を使用してオブジェクト、及びばねを作成することを示しました。
    属性:
      名前:(つまり、ビーンIDである)の名前を指定するために、現在の@Bean注釈方法でオブジェクトを作成します。
サンプルコード:
 / * 
*クラスの接続構成データベース
* @authorの馬プログラマ
* @Company http://www.ithiema.com 
* @Version 1.0 
* / 
パブリック クラスJdbcConfig {
 / ** 
*データソースを作成し、容器に春
* @return 
* / 
@Bean(名前 = "データソース" 公共データソースCreateDataSource(){
 試み{ 
ComboPooledDataSource DS = 新新ComboPooledDataSource(); 
ds.setUser( "ルート" ); 
ds.setPassword(「1234 " ); 
ds.setDriverClass( "はcom.mysql.jdbc.Driver "); 
Ds.setJdbcUrl( "JDBC:MySQLの:/// spring_day02" );
 を返すDSを; 
} キャッチ(はPropertyVetoException E){
 スロー 新しい新しいのRuntimeException(E); 
} 
} 
/ ** 
* QueryRunnerを作成し、また春に保存されています容器
* @param データソースが
* @return 
* / 
@Bean(名 = "ランナー" 
@Scope( "プロトタイプ" 公衆QueryRunner createQueryRunner(データソースデータソース){
 戻り 新しい新しいQueryRunner(データソース); 
} 
}  
注:
我々は、データソースを有し、 QueryRunnerは、あなたがbean.xmlを削除することができ、設定ファイルから削除しました。
構成ファイルが存在しないので、しかし、データ・ソース構成を作成し、クラスにコード化されています。それからそれらを構成する方法?
コメントを見てください。

  4。@ PropertySource

  役割:
    .propertiesファイルのファイル構成をロードするために使用されます。例えば、我々はデータソースを設定し、情報がデータベース接続に書き込むことができる
    プロパティの設定ファイルは、設定ファイルのプロパティの場所を指定するには、このアノテーションを使用することができます。
  属性:
    値は[]:ファイルの場所のプロパティを指定します。あなたがクラスパスにある場合は、クラスパスに記述する必要があります。

サンプル・コード:
コンフィギュレーション:
/ ** 
*接続構成クラスのデータベース
* @Version 1.0 
* / 
@PropertySource( "CLASSPATH:jdbcConfig.properties" パブリック クラスJdbcConfig { 
@value( "jdbc.driverの$ {}" プライベート文字列ドライバ; 
@value( "jdbc.urlの$ {}" プライベート文字列のURL; 
@value( "jdbc.usernameの$ {}" プライベート文字列名; 
@value( "jdbc.password $ {}" プライベート文字列のパスワード;
 / ** 
*データソースを作成し、春のコンテナに格納
* @return 
* / 
@Bean(名= "データソース" 公共のDataSource createDataSource(){
 しようと{ 
ComboPooledDataSource dsは = 新しい)ComboPooledDataSourceを(; 
ds.setDriverClass(ドライバ)。
ds.setJdbcUrl(URL); 
ds.setUser(ユーザー名); 
ds.setPassword(パスワード); 
戻るDSを。
} キャッチ(はPropertyVetoException電子){
 スロー 新規のRuntimeException(e)を、
} 
} 
} 
jdbc.properties文件:
jdbc.driver = はcom.mysql.jdbc.Driver 
jdbc.url = JDBC:MySQLの:// localhostを:3306 / spring_day02 
jdbc.username =ルート
jdbc.password = 1234 
注:
この時点で、我々は2つのクラスの構成を有しているが、彼らは何の関係もありません。どのように彼らの関係を構築するには?
コメントを見てください。

  5。@インポート

    効果:
      クラスを導入したとき、クラスの他の構成を導入するために、他の構成は、@Configuration注釈を書き込むことはできません。もちろん、書き込みが要求していない
      質問を。
    属性:
      値は[]:クラスのバイトコードの他の構成を指定します。

 

サンプルコード:
@Configuration 
@ComponentScan(basePackagesは = "com.itheima.spring" 
@import({JdbcConfig。クラス})
 パブリック クラスSpringConfiguration { 
} 
@Configuration // 書き込み線が書き込まれていない 
@PropertySource(「クラスパス:jdbc.properties " パブリック クラスJdbcConfig { 
} 
注:
我々が設定されているように構成する必要がありますが、何の設定ファイルが存在しないため、新たな問題が生じている、とどのようにコンテナにそれを取得するには?
次のセクションを参照してください。

 

  6.注釈を介して容器を取得 

ApplicationContextのAC = 
 新しい AnnotationConfigApplicationContext(SpringConfiguration。クラス);

 

  7.描画エンジニアリング構造

 

ここではシナリオが示してあります。

1. Mavenプロジェクトとインポート座標を作成します。

 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 }

 

おすすめ

転載: www.cnblogs.com/hujunwei/p/11135944.html