Spring配置和简单属性

来源:互联网 发布:c语言游戏源代码网站 编辑:程序博客网 时间:2024/04/28 03:34

在Spring文档中:

Annotation-based container configuration

如果我们要在Bean容器中配置一些相关信息和使用annotation,那么必须配置一下内容:主要是配置命名空间,什么样的标签应该遵守什么样的规范。
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:context="http://www.springframework.org/schema/context"     xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.0.xsd">   <context:annotation-config/></beans>



接下来看看简单属性配置,在官方文档中:

3.4.2.1 Straight values (primitives, Strings, and so on)

The value attribute of the <property/> element specifies a property or constructor argument as a human-readable string representation. As mentioned previously, JavaBeans PropertyEditors are used to convert these string values from a String to the actual type of the property or argument.

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"><!-- results in a setDriverClassName(String) call --><property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mydb"/><property name="username" value="root"/><property name="password" value="masterkaoli"/></bean>

The following example uses the p-namespace for even more succinct XML configuration.

<beans xmlns="http://www.springframework.org/schema/beans"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:p="http://www.springframework.org/schema/p"     xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"      destroy-method="close"      p:driverClassName="com.mysql.jdbc.Driver"      p:url="jdbc:mysql://localhost:3306/mydb"      p:username="root"      p:password="masterkaoli"/></beans>

The preceding XML is more succinct; however, typos are discovered at runtime rather than design time, unless you use an IDE such as IntelliJ IDEA or the SpringSource Tool Suite (STS) that support automatic property completion when you create bean definitions. Such IDE assistance is highly recommended.

You can also configure a java.util.Properties instance as:

<bean id="mappings"    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <!-- typed as a java.util.Properties --> <property name="properties">    <value>       jdbc.driver.className=com.mysql.jdbc.Driver       jdbc.url=jdbc:mysql://localhost:3306/mydb    </value> </property></bean>

一般情况下很少使用,但是像连接池,数据库的相关配置信息就可以这样用了。用<property    ..../>标签。







0 0
原创粉丝点击