1. 程式人生 > >Spring之Bean管理------註解方式

Spring之Bean管理------註解方式

編寫測試類

1,編寫相關的類

public interface UserDao {
public void sayHello();
}
public class UserDaoImpl implements UserDao {
@Override
public void sayHello() {
System.out.println("Hello Spring...");
} 
}

 

2,配置註解掃描

<!-- 指定掃描bean包下的所有類中的註解.base-package屬性是需要註解的類所在包的包名
  注意:掃描包時會掃描指定報下的所有子孫包,這個bean包是我自己建立的.

 -->
<context:component-scan base-package="bean"></context:component-scan>

3,在相關的類上添加註解

 

@Component(value="userDao")
public class UserDaoImpl implements UserDao {
@Override
public void sayHello() {
System.out.println("Hello Spring Annotation...");
}
}

 

4,編寫測試類

@Test
public void demo2() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//applicationContext.xml是在src下
UserDao userDao = (UserDao) applicationContext.getBean("userDao");
userDao.sayHello();
}

 

Spring 的 Bean 管理的中常用的註解

1 ,@Component:元件.(作用在類上)

Spring 中提供@Component 的三個衍生註解:(功能目前來講是一致的)

* @Controller :WEB 層

* @Service :業務層

* @Repository :持久層

這三個註解是為了讓標註類本身的用途清晰,Spring 在後續版本會對其增強

2,屬性注入的註解:(使用註解注入的方式,可以不用提供 set 方法.)

@Value :用於注入普通型別.

@Autowired :自動裝配: * 預設按型別進行裝配. * 按名稱注入: 如果有同一個類有兩個已經註解的例項,會比較麻煩

@Qualifier:強制使用名稱注入.

@Resource 相當於: @Autowired 和@Qualifier 一起使用.

3,Bean 的作用範圍的註解:

@Scope:

singleton:單例

prototype:多例

4,Bean 的生命週期的配置:

@PostConstruct :相當於 init-method

@PreDestroy :相當於 destroy-method

比如:

@Component("User")
@Scope(scopeName="singleton")//指定物件的作用範圍singleton是單例,prototype是多例
public class User {
    
    @Value(value="***")
    private String name;
    @Value(value="19")
    private Integer age;
    //@Autowired//自動裝配
    //@Qualifier("car2")
    
    @Resource(name="car2")
    private Car car;
//中間省略了get和set方法 @PostConstruct
public void init(){ System.out.println("初始化方法"); } @PreDestroy public void destory(){ System.out.println("銷燬方法"); } }