1. 程式人生 > 其它 >spring(註解開發)

spring(註解開發)

技術標籤:spring

Component(Repository,Service,Controller)

@Component
public class User {
    private int id;
    private String name;
    @Autowired
    private Address address;
}
@Component
public class Address {
    private String home;
    public void show(){
        System.out.println("這是我家"
); } }
  • Repository:data access object層
  • Service:service層
  • Controller:controller層

相當於<bean id="address" class="com.ckh.pojo.User"/>

    <!--開啟註解支援-->
    <context:annotation-config></context:annotation-config>
    
    <!--讓包裡註解生效-->
    <context:component-scan
base-package="com.ckh.pojo"/>

Value

@Component
public class User {
    private int id;

    @Value("ckh")
    private String name;
    @Autowired
    private Address address;
}

等於:

    <bean id="address" class="com.ckh.pojo.User">
        <property
name="name" value="ckh"/>
</bean>

自動裝配裝配(@Autowired)

輸入下面,自動新增xml約束

    <!--開啟註解支援-->
<context:annotation-config></context:annotation-config>
public class User {
    private int id;
    private String name;
    @Autowired
    private Address address;
}
    <bean id="address" class="com.ckh.pojo.Address"/>
    <bean name="user" class="com.ckh.pojo.User"/>

@Autowired先型別在名字
多個型別指定名字@Qualifier(“id”)

    @Autowired
    @Qualifier("address")
    private Address address;

也可以使用java自帶註解resource

javaCofig替代xml

@Configuration
public class CkhConfig {
    @Bean
    public User getUser(){
        return new User();
    }
}
public class MyTest {
    public static void main(String[] args) {
        //獲取上下文
        ApplicationContext context = new AnnotationConfigApplicationContext(CkhConfig.class);
        User user = (User) context.getBean("getUser");
        System.out.println(user.getName());
    }
}