@Commponent
?使用@Component注解代替<bean>標簽
<!--注解掃描:掃描指定的基本包及其子包下的類,識別使用了@Component注解的文件--><context:component-scan base-package="org.xfy"></context:component-scan>
?
package org.xfy.Dao.Impl;import org.springframework.stereotype.Component;
import org.xfy.Dao.UserDao;
//當注解的屬性只有一個且為value的時候 在注解中value可以省略不寫
@Component("userDao")
public class UserDaoImpl implements UserDao {
}
?注意:@Component注解開發不指定id的話,那就是類名首字母小寫
?
@Component注解開發不指定id的話,那就是類名首字母小寫
@Service、@Componet 定義的 bean name 的生成規則如下: 優先取注解中的 value 指定的名字做為 bean name。 如果注解中沒有指定的話,默認情況下是類名小寫,例如: “mypackage.MyJdbcDao” -> “myJdbcDao” 注意有兩種特殊的情況:
-
如果 bean 是內部類的話,因此將會是 “outerClassName.InnerClassName” 形式的名稱
-
如果類名是連續2個首字母大寫的話,bean name 就是類名,例如:“mypackage.MYJdbcDao” -> “MYJdbcDao”
@Bean 定義的 bean name 的生成規則是: 優先取注解中 name 指定的名字做為 bean name。 如果注解中沒有指定的話,就取 methodName 做為 bean name。
?
?
package org.xfy.Dao.Impl;import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.xfy.Dao.UserDao;import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;//當注解的屬性只有一個且為value的時候 在注解中value可以省略不寫
@Component("userDao")
@Scope(scopeName = "singleton")
@Lazy(value = false)
public class UserDaoImpl implements UserDao {public UserDaoImpl() {System.out.println("初始化");}@PostConstructvoid init(){System.out.println("初始化方法");}@PreDestroyvoid destory(){System.out.println("銷毀方法");}
}
?其他注解
?
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//package org.springframework.stereotype;import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {@AliasFor(annotation = Component.class)String value() default "";
}