1. 程式人生 > 其它 >spring的學習日記-spring-IOC-基於註解的方式開發-半註解

spring的學習日記-spring-IOC-基於註解的方式開發-半註解

基於半註解的方式開發:

我們在使用註解開發的時候需要注意:

1.在xml中配置相關的資源,

2.在xml中開啟支援註解開發

3.在xml中配置,使具體包下面的類的註解生效

4.在pojo層的註解為:@Component

在dao層的註解為:@Repository

在service層下面的註解為:@Service

在control層下面的註解為:@Controller

以上的註解就相當於在xml中註冊相應的bean,也就是new一個物件

pojo層:

package com.fu.pojo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; @Component public class User { @Value("1") private int id; @Value("張三") private String name; @Value("123456") private String pwd; public User(int id, String name, String pwd) { this.id = id; this.name = name;
this.pwd = pwd; System.out.println("有參構造建立物件"); } public User() { System.out.println("無參構造建立物件"); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; }
public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}'; } }

xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

<!--    開啟註解的方式-->
    <context:annotation-config/>

<!--    使對應包下面的類生效-->
    <context:component-scan base-package="com.fu.pojo"/>

</beans>

測試類:

import com.fu.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {

    public static void main(String[] args) {
        //獲取IOC容器
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        //有了容器我們就get到what
        User user = context.getBean("user", User.class);
        System.out.println(user);

    }
}

測試結果: