上一篇文章我們學習了使用注解開發,但還沒有完全脫離xml的配置,現在我們來學習JavaConfig配置來代替xml的配置,實作完全注解開發,
下面我們用一個簡單的例子來進行學習,
一、首先建立兩個物體類
User:
package com.jms.pojo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class User { @Value("jms") private String name; private Address address; public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } @Autowired public void setAddress(Address address) { this.address = address; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", address=" + address.toString() + '}'; } }
Address:
package com.jms.pojo; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class Address { @Override public String toString() { return "Address{" + "id=" + id + '}'; } @Value("100") private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } }
兩個簡單的類,并且實作了值的注入和Bean的自動裝配,
二、建立一個配置類
package com.jms.config; import com.jms.pojo.Address; import com.jms.pojo.User; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; //@Configuration代表他是一個配置類,可以看作原來的xml檔案,它本身還是一個@Component,所以它也被注冊到Spring容器中,由Spring容器托管 @ComponentScan("com.jms.pojo") @Configuration public class JmsConfig { //這一個方法就相當于xml中的一個Bean標簽,方法名對應id屬性,回傳值對應class屬性 @Bean public Address address() { return new Address(); } @Bean public User getUser() { return new User(); } }
這個配置類的作用就是代替原來的xml組態檔,所以xml檔案中有的功能這里基本上都可以配置,
上面只簡單配置了最基礎的Bean和ComponentScan掃描包,
三、測驗
@Test public void test1() { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(JmsConfig.class); User user = applicationContext.getBean("getUser", User.class); System.out.println(user); }

注意點:
1.我們new的不再是ClassPathXmlApplicationContext物件,而是AnnotationConfigApplicationContext;
2.getBean方法中傳入的是配置類里的方法名,因為方法名對應原來xml里的id,
(本文僅作個人學習記錄用,如有紕漏敬請指正)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/509569.html
標籤:其他
上一篇:SpringCloud 學習總結
