使用注解之前要開啟自動掃描功能
其中base-package為需要掃描的包(含子包)。
<context:component-scan base-package="cn.test"/>@Configuration把一個(gè)類作為一個(gè)IoC容器,它的某個(gè)方法頭上如果注冊了@Bean,就會作為這個(gè)Spring容器中的Bean。@Scope注解 作用域@Lazy(true) 表示延遲初始化@Service用于標(biāo)注業(yè)務(wù)層組件、@Controller用于標(biāo)注控制層組件(如struts中的action)@Repository用于標(biāo)注數(shù)據(jù)訪問組件,即DAO組件。@Component泛指組件,當(dāng)組件不好歸類的時(shí)候,我們可以使用這個(gè)注解進(jìn)行標(biāo)注。@Scope用于指定scope作用域的(用在類上)@PostConstruct用于指定初始化方法(用在方法上)@PreDestory用于指定銷毀方法(用在方法上)@DependsOn:定義Bean初始化及銷毀時(shí)的順序@Primary:自動裝配時(shí)當(dāng)出現(xiàn)多個(gè)Bean候選者時(shí),被注解為@Primary的Bean將作為首選者,否則將拋出異常@Autowired 默認(rèn)按類型裝配,如果我們想使用按名稱裝配,可以結(jié)合@Qualifier注解一起使用。如下:@Autowired @Qualifier("personDaoBean") 存在多個(gè)實(shí)例配合使用@Resource默認(rèn)按名稱裝配,當(dāng)找不到與名稱匹配的bean才會按類型裝配。@Async異步方法調(diào)用,需要添加以下代碼
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"><property name="corePoolSize" value="10"/><property name="maxPoolSize" value="300"/></bean><task:annotation-driven/>
@value
在spring 3.0中,可以通過使用@value,對一些如xxx.properties文件 中的文件,進(jìn)行鍵值對的注入,例子如下: 1 首先在applicationContext.xml中加入: <beans xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"> </beans> 的命名空間,然后 2 <util:properties id="settings" location="WEB-INF/classes/META-INF/spring/test.properties" /> 3 創(chuàng)建test.properties 內(nèi)容abc=123 4 import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping("/admin/images") @Controller public class ImageAdminController { @Value("#{settings['abc']}") private String imageDir;@Value("/WEB-INF/test.properties") private File testProperties;
} 這樣就將test.abc的值注入了imageDir中了,文件也注入到testProperties了
新聞熱點(diǎn)
疑難解答
圖片精選