peter tong

Ranch Hand
+ Follow
since Mar 15, 2008
Merit badge: grant badges
For More
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
4
Received in last 30 days
0
Total given
78
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by peter tong

Tim Holloway wrote:You don't use operator new for Spring. Spring expects to handle instantiation internal to its bean factory. Only non-Spring beans should be constructed with new or its equivalents. Note also that a bean constructed with new is external to Spring, so it doesn't get the Spring benefits such as auto-wiring. So where possible make all your beans be Spring Beans.

Spring's bean factory constructs singleton instances by default. Note that when I say "singleton" here, I mean that there's a single instance, not that it's classically Singleton, with the enforcement mechanisms for ensuring that the bean is totally and forever singleton. The only enforcement would be Spring itself.

Spring singleton instances can be, and often are stateful.  But a stateful singleton object's primary purpose is to ensure single definitive property values between all participants. Often, however, there are only 2 participants because Spring does so much of what it does by wiring standard components together. So that's OK. If there are more participants, and especially if there are Threads involved, Spring does not enforce synchronization, so that's something the bean itself would be obliged to deal with.



NO, spring singleton instances is stateless, its field is shared by all request.
But after searching on Web, I find some different of using singleton bean than static method,
e.g. singleton bean can override interface method, static method cannot.
https://www.baeldung.com/java-static-class-vs-singleton
3 months ago
No comparing Creating multiple copies of a bean and create a bean with spring bean with singleton scope, but comparing a class with just static method and static final fields (so this is stateless?) with spring bean with singleton scope.
3 months ago

Stephan van Hulst wrote:Stateless means that an object doesn't evolve over time. Its fields are assigned a value when the object is constructed, and they don't change afterwards. The best example of stateless objects are immutable objects, because they CAN'T change after they've been created.

Stateful objects are those that have an internal state that changes over time.

Now, I really don't like how all online guides just say: singletons are stateless and prototypes are stateful. It completely misses the point, and it doesn't offer an insight into why most applications are set up that way.

Roughly speaking, your web application consists of two types of objects. The first type are services with a lifetime that is longer than a single request, i.e. they can be used by more than one request, often even by multiple requests simultaneously. These services usually have the singleton scope: you create them once, and they are reused for the duration of the application.

The second type are objects that are needed only temporarily. They are created at some point during the lifetime of a single request, used, and then discarded again. They are not shared between different requests, and often they are not even used outside of the method where they are first needed. These objects have the prototype scope: a new instance of them is created every time they are injected.

It doesn't really matter whether prototypes are stateful or not. Just design them any way you require.

Singletons on the other hand MUST be stateless. Because they are shared between different requests, they can be accesses by multiple threads at the same time. This means they need to be thread-safe. To make an object thread-safe, you have two options:

The first option is to use concurrency utilities to carefully synchronize access to the object. The problem with this approach is that it causes requests to block until other requests are finished with the shared service. For high traffic websites, this approach is a no-go.

The second option is to make the class stateless. An object that doesn't change its internal state can be used by multiple requests simultaneously, without blocking.



Sorry but still has some unknown, if create a stateless object that doesn't change its internal state, then is this like create a class with all static member and static method? Why need create such Singleton, stateless object (bean) in spring?
3 months ago

Himai Minh wrote:You may want to read this https://nullbeans.com/prototype-vs-singleton-spring-beans-differences-and-uses/ .
It says that singleton is good for resource intensive components such as database service component. You don't want to create a new database component
when you need to connect to the database.



the post still just said
Singleton:Used in stateless situations.
Prototype:Used for stateful situations.

NO explanation and no example of what is stateless/stateful situation, WHY stateless choose singeleton, stateful choose prototype

And has no information for my question for entity object (value object) like Users Class, SalesOrder class....these are stateless or stateful? Or use new operator is better....

In fact, I search many article and most just said WHAT is singleton or prototype scope and just one statement said stateless choose singleton and stateful choose prototype, but no more detail explanation of WHY has this rule.
3 months ago
1) And why default is Singleton Scope?
For some domain object like Class SalesOrder.
If the SalesOrder object is singleton, then mean all request will use the same SalesOrder object? then all user will overwirte the same SalesOrder object?
Or for domain object, we should use @Prototype Scope? Or better just use new operator?

2) Any guideline for when to use Spring Singleton scope, prototype scope and when to use just java new operator?

3) for spring documentation, it mentions

As a rule, you should use the prototype scope for all stateful beans and the singleton scope for stateless beans.



any example of what is stateful beans and what is stateless beans?
Usually service layer, data access layer, controller layer is stateless beans? (As there is @Service, @Repository and @Controller stereotype annotation, and spring default is singleton scope, so I guess this three layer is stateless beans).

Sorry than my concept for when to use which bean scope is poor.
3 months ago
why is the result like this?

4 months ago
when I press finished, all project, even the checkbox is unchecked, still imported into my workspace
as in this image
https://postimg.cc/PPjPbnf2
7 months ago
I download the source in https://github.com/eugenp/tutorials as a zip folder, then in eclipse, I use import > existing maven projects > then in root directory, select the folder where parent pom.xml located, it prompt a tree of project and I select only one of it. but when I press finished, all project, even the checkbox is unchecked, still imported into my workspace, why?



7 months ago
Finally I check that with unknown reason, in sts build path, src/main/resources, excluded is *.*, after change it to none,  the greeting.html can be found in \target\classes\templates
7 months ago
I just follow the tutorial in
https://spring.io/guides/gs/serving-web-content/

I use eclipse sts.
there is greeting.html under src/main/resources/templates
and in pom.xml, there is dependency


when I start the application, I see this warning:

WARN 9620 --- [  restartedMain] ion$DefaultTemplateResolverConfiguration : Cannot find template location: classpath:/templates/ (please add some templates, check your Thymeleaf configuration, or set spring.thymeleaf.check-template-location=false)



and when I run the application and type
http://localhost:8080/greeting

error:


org.thymeleaf.exceptions.TemplateInputException: Error resolving template [greeting], template might not exist or might not be accessible by any of the configured Template Resolvers
at org.thymeleaf.engine.TemplateManager.resolveTemplate(TemplateManager.java:869) ~[thymeleaf-3.1.0.RELEASE.jar:3.1.0.RELEASE]
......


is shown, why will this happen?

the project layout is shown as follow:


7 months ago
I follow the sample in
https://spring.io/guides/gs/accessing-data-mysql/
it run successfully, then I try to change it to connect to my local sql server, so I add

in pom.xml, and in application.properties, I change it to

and then in my run configuration, I kept it unchange, that is,
java 17, -cp accessing-data-mysql-complete
com.example.accessingdatamysql.AccessingDataMysqlApplication


then I run this configuration, but now error:


java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520) at java.base/java.lang.Class.forName0(Native Method) at java.base/java.lang.Class.forName(Class.java:467) at org.springframework.util.ClassUtils.forName(ClassUtils.java:283) at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.driverClassIsLoadable(DataSourceProperties.java:190) at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName(DataSourceProperties.java:171) at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.initializeDataSourceBuilder(DataSourceProperties.java:123) at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.createDataSource(DataSourceConfiguration.java:48) at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari.dataSource(DataSourceConfiguration.java:90) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:568) .......



is shown, why? the same run configuration is success to run the mysql sample.

2) and in intellij console, I cannot see what classpath it is using, any method to show the classpath this run configuration is using?

3) in intellij project settings > Modules > Dependencies, I just see
Maven: com.mysql:mysql-connector-j:8.0.31
but no
mssql-jdbc
although my pom.xml has it, why?


7 months ago

peter tong wrote:I try to use

in connection string, then now error
c.m.s.j.internals.SQLServerConnection    : ConnectionID:5 ClientConnectionId: xxxxxx-xxxx Prelogin error: host localhost port 1434 Error reading prelogin response: Connection reset ClientConnectionId:xxxxxx-xx.......-xxx
keep throwing.



ok now, the port number should be 1433, not 1434.
so the critical step is add trustServerCertificate=true in connection string
7 months ago
I try to use

in connection string, then now error
c.m.s.j.internals.SQLServerConnection    : ConnectionID:5 ClientConnectionId: xxxxxx-xxxx Prelogin error: host localhost port 1434 Error reading prelogin response: Connection reset ClientConnectionId:xxxxxx-xx.......-xxx
keep throwing.
7 months ago
I use spring boot and want to connect to my local sql server, but when run spring-boot:run, following message is shown:


2023-02-04T21:46:03.787+08:00 ERROR 12268 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception during pool initialization.
com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target". ClientConnectionId:98f8f85b-4248-4ab3-bc6b-95c305d53992
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:3806) ~[mssql-jdbc-11.2.1.jre17.jar:na]
at com.microsoft.sqlserver.jdbc.TDSChannel.enableSSL(IOBuffer.java:1906) ~[mssql-jdbc-11.2.1.jre17.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:3329) ~[mssql-jdbc-11.2.1.jre17.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2950) ~[mssql-jdbc-11.2.1.jre17.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2790) ~[mssql-jdbc-11.2.1.jre17.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1663) ~[mssql-jdbc-11.2.1.jre17.jar:na]
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1064) ~[mssql-jdbc-11.2.1.jre17.jar:na]
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:138) ~[HikariCP-5.0.1.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:359) ~[HikariCP-5.0.1.jar:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201) ~[HikariCP-5.0.1.jar:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:470) ~[HikariCP-5.0.1.jar:na]
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:561) ~[HikariCP-5.0.1.jar:na]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:100) ~[HikariCP-5.0.1.jar:na]
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112) ~[HikariCP-5.0.1.jar:na]
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:284) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:177) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:36) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:119) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:255) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:230) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.hibernate.boot.model.relational.Database.<init>(Database.java:44) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.getDatabase(InFlightMetadataCollectorImpl.java:218) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:191) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:138) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1350) ~[hibernate-core-6.1.5.Final.jar:6.1.5.Final]
........



anyway, if connect to mysql, not this error occured,
so what is the problem?

my application.properties for connction to mssql server is as follow:


spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:sqlserver://localhost;databaseName=db_example
spring.datasource.username=sa
spring.datasource.password=xxxxxxxx
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver



and for my sql is as follow


spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username=springuser
spring.datasource.password=ThePassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver


7 months ago